[英]A livedata in a viewmodel can just observed by one place?
I have a livedata in a viewmodel. 我在viewmodel中有一个livedata。 and i observe the livedata in a fragment, another class,
我在另一个片段中观察实时数据
when i change the livedata value, only the fragment can receive the notification of livedata change. 当我更改livedata值时,只有片段可以接收livedata更改的通知。 not another class.
没有别的课程。
i wonder just only one place(ex: fragment, activity etc) can observe a livedata of viewmodel? 我想知道只有一个地方(例如片段,活动等)可以观察viewmodel的实时数据吗?
You are not getting it right. 您做对了。 The way MVVM works is view interact with viewModel which is observer class and viewModel then interacts with repo class for db/remote operations.
MVVM的工作方式是,视图与作为观察者类的viewModel进行交互,然后viewModel与用于数据库/远程操作的repo类进行交互。 Reason why you are observing live data in fragment/activity is because as per design patter view can only access ViewModel that's why you are only able to observe it from fragment/activity class
之所以要观察片段/活动中的实时数据,是因为按照设计模式视图只能访问ViewModel,这就是为什么您只能从片段/活动类中观察它的原因
The livedata can be observed by as many observers as you want.The observer if implements LifecycleOwner interface will get notified when in running state or you can observe it forever irrespective of lifecycle of the observer by using observeForever. 实时数据可以由任意数量的观察者观察。观察者(如果实现了LifecycleOwner接口)将在运行状态下得到通知,或者您可以使用observeForever永久观察该数据,而不管观察者的生命周期如何。 But you will have to manually remove the observer to stop observing it.
但是您将必须手动删除观察者以停止对其进行观察。
LiveData considers an observer, which is represented by the Observer class, to be in an active state if its lifecycle is in the STARTED
or RESUMED
state. LiveData考虑观察者,这是由该观察类表示,要在活动状态中,如果它的生命周期在
STARTED
或RESUMED
状态。 LiveData only notifies active observers about updates. LiveData仅将有关更新的信息通知活动的观察者。 Inactive observers registered to watch LiveData objects aren't notified about changes.
注册为观看LiveData对象的非活动观察者不会收到有关更改的通知。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.