从前台服务观察 LiveData [英] Observe LiveData from foreground service

查看:36
本文介绍了从前台服务观察 LiveData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储 LiveData 对象的存储库,两者都使用活动和前台服务通过 ViewModel.当我从活动开始观察时,一切都按预期进行.然而,从服务观察不会触发观察.这是我使用的代码

I have a repository which holds the LiveData object and is used by both activity and a foreground service through a ViewModel. When I start observing from the activity everything works as expected. However observing from the service doesn't trigger the Observe. This is the code I use

class MyService: LifecycleService() {
     lateinit var viewModel: PlayerServiceViewModel

     override fun onCreate() {
          viewModel = MyViewModel(applicationContext as Application)
     }

     override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
          viewModel.getLiveData().observe(this, Observer { data ->
            // Do something with the data
        })
     }
}

知道为什么它不起作用并且我没有收到数据吗?

Any ideas why it doesn't work and I don't receive the data?

推荐答案

我在 LifecycleActivityFragments 中使用了 ViewModelLiveData 它按预期工作并观察数据.

I used ViewModel with LiveData in LifecycleActivity and Fragments it works and observes data as expected.

遇到您的问题,当您从 Service 或任何其他 Activity 创建 new ViewModel 时,它会创建 <ViewModel 从 Repository 和最终 DAO 查询所需的所有 LiveData 和其他依赖项的强>新实例.如果您没有为两个 ViewModel 使用相同的 DAO,您的 LiveData 可能不会更新,因为它正在观察 不同 DAO 实例.

Coming to your problem, when you create new ViewModel from Service or any another Activity it creates new instance of all the LiveData and other dependencies required for ViewModel to query from Repository and ultimately DAO. If you are not using the same DAO for both ViewModels your LiveData may not update as it is observing on different instance of DAO.

我在我的项目中使用了 Dagger2 来维护 DAO 和其他常见依赖项的单例实例.因此,您可以尝试使您的存储库和 DAO 单独,以使其在整个应用程序中保持一致.

I used Dagger2 in my project to maintain Singleton instances for DAO and other common dependencies. So you can try making your Repository and DAO singleton to keep it consistent across the Application.

我尝试将它与 ServicesLifecycleService 一起使用,并具有相同的流程,它对我有用.

I tried it using with Services with LifecycleService with same flow and it worked for me.

当数据从 null 变为拉取数据时,我得到以下输出

I got following output when data changed form null to pulled data

D/ForegroundService: onStartCommand: Resource{status=LOADING, message='null', data=null}
D/ForegroundService: onStartCommand: Resource{status=SUCCESS, message='null', data=TVShow(id=14,...

起初它显示空数据,因为数据库中不存在数据从网络中提取数据并更新到数据库后Observer自动观察数据.

At first it showed null data as data wasn't present in database After pulling data from network and updating into database Observer observed data automatically.

使用以下代码解决

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);
    }
}

这篇关于从前台服务观察 LiveData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆