Android:从服务在 ViewModel 中设置 LiveData

发布于 2025-01-15 15:49:27 字数 336 浏览 1 评论 0原文

我设置应用程序的方式是,服务将在后台获取一些信息,这些信息需要由片段实时获取,然后显示它进入一个视图。为此,我将数据放入 ViewModel 中,并让我的 Fragment 观察 ViewModel 中的 LiveData。

问题是,我在 设置/更改 ViewModel 类中的 LiveData 时遇到问题 看来 ViewModel 是要在 Activity 和 Fragments 之间使用的,而且我似乎无法在我的服务中获取 ViewModel 来更改我的 Fragment 需要观察的值。有办法实现吗?

The way I have my app set up is that, the Service will be getting some information in the background, which needs to be acquired live by the Fragment, and then display it into a view. To do this, I put the data inside a ViewModel and let my Fragment observe the LiveData in the ViewModel.

The problem is, I am having trouble setting/changing the LiveData inside the ViewModel class from the service. It seems that ViewModel is meant to be used between Activities and Fragments, and I cannot seem to get the ViewModel inside my service in order to change the value that needs to be observed by my Fragment. Is there a way to implement this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幸福丶如此 2025-01-22 15:49:27

您可能希望使用具有自己的 MutableLiveData 字段的存储库,该字段在您的服务中进行修改。然后,您的 ViewModel 将有一个指向 Repository 字段的 MutableLiveData 字段,并且您的 Fragment 可以观察该字段。

片段:

...
viewModel.myData.observe(viewLifecycleOwner) { myData ->
    // handle new data observed
}
...

ViewModel:

// Need to clear repo reference in [onCleared] to avoid resource leaks
private var _myData: MutableLiveData<MyData>? = myRepo.myData
val myData: MutableLiveData<MyData> = _myData
...
override fun onCleared() {
    super.onCleared()
    _myData = null
}

存储库:

val myData = MutableLiveData<MyData>() // or whatever source (Room, etc.)

服务:

...
Repository.getInstance().myData.postValue(/* some new info */)
...

You probably want to use a Repository with its own MutableLiveData field that is modified within your service. Your ViewModel will then have a MutableLiveData field that points to the Repository field, and your Fragment can observe that field.

Fragment:

...
viewModel.myData.observe(viewLifecycleOwner) { myData ->
    // handle new data observed
}
...

ViewModel:

// Need to clear repo reference in [onCleared] to avoid resource leaks
private var _myData: MutableLiveData<MyData>? = myRepo.myData
val myData: MutableLiveData<MyData> = _myData
...
override fun onCleared() {
    super.onCleared()
    _myData = null
}

Repository:

val myData = MutableLiveData<MyData>() // or whatever source (Room, etc.)

Service:

...
Repository.getInstance().myData.postValue(/* some new info */)
...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文