I used ViewModel
with LiveData
in LifecycleActivity
and Fragments
它按预期工作并观察数据。
当你创建时遇到你的问题new ViewModel
from Service
或任何其他Activity
它创建新实例所需的所有 LiveData 和其他依赖项ViewModel
从存储库查询并最终从 DAO 查询。
如果您没有为两个 ViewModel 使用相同的 DAO,那么您的LiveData
可能不会更新因为它正在观察不同的DAO 实例.
I used Dagger2
在我的项目中维护 DAO 和其他常见依赖项的 Singleton 实例。所以你可以尝试制作你的存储库和 DAO单例以在整个应用程序中保持一致。
我尝试使用Services
with LifecycleService
以相同的流程,它对我有用。
当数据从 null 更改为拉取数据时,我得到以下输出
D/ForegroundService: onStartCommand: Resource{status=LOADING, message='null', data=null}
D/ForegroundService: onStartCommand: Resource{status=SUCCESS, message='null', data=TVShow(id=14,...
起初它显示空数据,因为数据库中不存在数据
从网络提取数据并更新到数据库后Observer
自动观察数据。
使用以下代码进行了计算
public class ForegroundService extends LifecycleService {
private static final String TAG = "ForegroundService";
private TVShowViewModel tvShowViewModel;
private TVShow tvShow;
@Inject TVShowDataRepo tvShowDataRepo;
@Override
public void onCreate() {
super.onCreate();
AndroidInjection.inject(this);
tvShowViewModel = new TVShowViewModel(tvShowDataRepo);
tvShowViewModel.init(14);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
tvShowViewModel.getTVShow().observe(this, tvShowResource -> {
Log.d(TAG, "onStartCommand: " + tvShowResource);
});
return super.onStartCommand(intent, flags, startId);
}
}