在 ViewModel 构造函数上初始化 LiveData
Initializing LiveData on ViewModel constructor
我只是 android 编程的初学者。最近我正在阅读有关房间数据库如何 return 在对数据库进行更改时自动更新实时数据的信息。我正在使用视图模型 class 实例来保存我的 Livedata,如下所示
public class LogVM extends AndroidViewModel{
MasterDatabase roomDatabase;
LiveData<List<Log>> logData;
LogVM(Application application){
super(application);
roomDatabase=MasterDatabase.getInstance(application);
logData=roomDatabase.getLogDao.getAllLogs();
}
public LiveData<List<Log>> getLogData() {
return logData;
}
}
上面的代码实际上工作正常。但是我的问题是在构造函数中初始化logdata的时候,我们运行数据库操作不是在主线程吗?但是代码在没有任何警告的情况下编译和运行。有人可以解释一下吗?抱歉,这是一个愚蠢的问题。但我只是一个初学者!
Room 将为您创建代码,以确保在执行您的数据库代码时将其安排在后台线程上。如果您查看生成的代码,您会发现 DAO classes 使用一个名为 ComputableLiveData
的内部 class,它使用 IOThreadExecutor
来执行其工作。
文档中对此有简要说明。
https://developer.android.com/topic/libraries/architecture/livedata
The Room persistence library supports observable queries, which return LiveData objects. Observable queries are written as part of a Database Access Object (DAO).
Room generates all the necessary code to update the LiveData object when a database is updated. The generated code runs the query asynchronously on a background thread when needed. This pattern is useful for keeping the data displayed in a UI in sync with the data stored in a database. You can read more about Room and DAOs in the Room persistent library guide.
我只是 android 编程的初学者。最近我正在阅读有关房间数据库如何 return 在对数据库进行更改时自动更新实时数据的信息。我正在使用视图模型 class 实例来保存我的 Livedata,如下所示
public class LogVM extends AndroidViewModel{
MasterDatabase roomDatabase;
LiveData<List<Log>> logData;
LogVM(Application application){
super(application);
roomDatabase=MasterDatabase.getInstance(application);
logData=roomDatabase.getLogDao.getAllLogs();
}
public LiveData<List<Log>> getLogData() {
return logData;
}
}
上面的代码实际上工作正常。但是我的问题是在构造函数中初始化logdata的时候,我们运行数据库操作不是在主线程吗?但是代码在没有任何警告的情况下编译和运行。有人可以解释一下吗?抱歉,这是一个愚蠢的问题。但我只是一个初学者!
Room 将为您创建代码,以确保在执行您的数据库代码时将其安排在后台线程上。如果您查看生成的代码,您会发现 DAO classes 使用一个名为 ComputableLiveData
的内部 class,它使用 IOThreadExecutor
来执行其工作。
文档中对此有简要说明。 https://developer.android.com/topic/libraries/architecture/livedata
The Room persistence library supports observable queries, which return LiveData objects. Observable queries are written as part of a Database Access Object (DAO).
Room generates all the necessary code to update the LiveData object when a database is updated. The generated code runs the query asynchronously on a background thread when needed. This pattern is useful for keeping the data displayed in a UI in sync with the data stored in a database. You can read more about Room and DAOs in the Room persistent library guide.