简体   繁体   English

android第一次在ViewModel中初始化LiveData怎么办? 使用哪个工厂?

[英]How to initialize the LiveData in ViewModel for the first time in android? and which factory to use?

I want to initialize the LiveData value when the app is launched, not every time the orientation changes.我想在应用程序启动时初始化 LiveData 值,而不是每次方向改变时。 Can I use the constructor of the subclass of ViewModel for it?我可以使用 ViewModel 的子类的构造函数吗?

Instead of LiveData which pushes the last value to observers for every config change (like a RxJava BehaviourSubject ), you should use something which pushes the event once.而不是LiveData将最后一个值推送给每个配置更改的观察者(如 RxJava BehaviourSubject ),您应该使用将事件推送一次的东西。

You can use:您可以使用:

  • SingleLiveEvent : Send the event to only 1 observer, check here and here or alternatives here SingleLiveEvent :仅将事件发送给 1 个观察者,检查此处此处此处的替代方案
  • LiveEvent : Send the event to all the observers, check here LiveEvent : 发送事件给所有观察者,勾选这里

Both of those approaches will not cache events, which means that an observer should be already observing the *LiveEvent to receive it这两种方法都不会缓存事件,这意味着观察者应该已经在观察*LiveEvent以接收它

You can find articles online about alternative approaches but the philosophy behind them is probably the same您可以在网上找到有关替代方法的文章,但它们背后的理念可能是相同的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM