最近我正在探索谷歌最近推出的 Android 架构。从 文档 中我发现了这个:
public class MyViewModel extends ViewModel {
private MutableLiveData<List<User>> users;
public LiveData<List<User>> getUsers() {
if (users == null) {
users = new MutableLiveData<List<Users>>();
loadUsers();
}
return users;
}
private void loadUsers() {
// do async operation to fetch users
}
}
活动可以按如下方式访问此列表:
public class MyActivity extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
model.getUsers().observe(this, users -> {
// update UI
});
}
}
我的问题是,我要这样做:
在
loadUsers()
函数中,我异步获取数据,我将首先检查数据库(房间)中的数据如果我没有在那里获取数据,我将调用 API 从 Web 服务器获取数据。
我会将获取的数据插入数据库(房间)并根据数据更新 UI。
推荐的方法是什么?
If I start a Service
to call the API from the loadUsers()
method, how can I update the MutableLiveData<List<User>> users
variable from that Service
?
原文由 S Haque 发布,翻译遵循 CC BY-SA 4.0 许可协议
我假设您正在使用 android 架构组件。实际上,无论您在哪里调用
service, asynctask or handler
来更新数据都无关紧要。您可以使用postValue(..)
方法从服务或异步任务中插入数据。您的课程将如下所示:由于
users
是LiveData
,Room
数据库负责在任何插入位置提供用户数据。Note:
在类似MVVM的架构中,repository主要负责检查和拉取本地数据和远程数据。