[英]How to use Room Database Viewmodel Observer in Android Foreground Service
I have following view model and observer in A Fragment(in onViewCreated
) which populates the recyelerview using adapter我在片段(在
onViewCreated
)中有以下视图模型和观察者,它使用适配器填充 recyelerview
commonOwnDBViewModel =
new ViewModelProvider(requireActivity()).get(CommonOwnDBViewModel.class);
Observer<List<FolderEntity>> notesObserver =
FolderEntityList -> {
folderNameAdapter.setListManager(FolderEntityList);
recyclerView.getAdapter().notifyDataSetChanged();
Toast.makeText(mActivity, "" + FolderEntityList.size(), Toast.LENGTH_SHORT).show();
};
commonOwnDBViewModel.getAllFolderEntityList
().observe(requireActivity(), notesObserver);
it gives me a list and works fine in the fragment now I want to use the same list in A service using Viewmodel and Observer how can we do that how do we manage Lifecycle in service.它给了我一个列表并且在片段中工作正常,现在我想在使用 Viewmodel 和 Observer 的服务中使用相同的列表,我们如何做到这一点,我们如何管理服务中的生命周期。
Instead of using normal service, use LifecycleService
.不要使用普通服务,而是使用
LifecycleService
。
You can get the lifecycle of the service by calling getLifecycle()
method and pass this lifecycle to your observer.您可以通过调用
getLifecycle()
方法获取服务的生命周期并将此生命周期传递给您的观察者。
More details here: https://developer.android.com/reference/androidx/lifecycle/LifecycleService更多细节在这里: https : //developer.android.com/reference/androidx/lifecycle/LifecycleService
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.