Observing LiveData from ViewModel

后端 未结 6 2036
-上瘾入骨i
-上瘾入骨i 2021-01-30 05:07

I have a separate class in which I handle data fetching (specifically Firebase) and I usually return LiveData objects from it and update them asynchronously. Now I want to have

6条回答
  •  无人共我
    2021-01-30 05:35

    I know there have already been amazing answers for this topic, but I wanted to add my own as well:

    If you want to stick to LiveData you can always use Transformations.map so that you don't have to observe in the ViewModel but rather only in the Fragment/Activity.

    Otherwise, you can use SharedFlow, a single event observable. For more, I have written an article here: https://coroutinedispatcher.com/posts/decorate_stateful_mvvm/

    You don't have to pass viewLifecycleOwner in the ViewModel because there is no point in calling observe in the ViewModel when the View just needs the latest result after all.

提交回复
热议问题