我在LifecycleActivity
和Fragments
中使用了ViewModel
和LiveData
,并且它按预期工作并观察数据。
谈到你的问题,当你从Service
或其他Activity
创建新的ViewModel
时,它会创建所有LiveData和其他依赖项的新实例,以便ViewModel
可以从Repository查询,最终到DAO。
如果你没有为两个ViewModels使用相同的DAO,那么你的LiveData
可能不会更新,因为它正在观察不同 DAO实例。
我在我的项目中使用了Dagger2
来维护DAO和其他常见依赖项的Singleton实例。因此,你可以尝试将你的Repository和DAO设置为singleton,以保持跨应用程序的一致性。
我在LifecycleService
中使用了相同的流程与Services
一起尝试了它,并且它对我有用。
当数据从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);
}
}
super.onCreate()
和super.onStartCommand()
引起的。在更新AS和kotlin插件后,我发现它们开始抱怨缺少这些调用,然后我意识到了这个问题。 - Ilya SosisLifecycleService
时,我遇到了这个异常: 如果我搜索一下,通常这个错误会出现在IntentService中,但这不是一个IntentService。我有正确的注入。你有什么想法如何解决这个问题吗? - Wahib Ul Haq