Varun S
Varun S

Reputation: 53

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. Can I use the constructor of the subclass of ViewModel for it?

Upvotes: 1

Views: 416

Answers (1)

MatPag
MatPag

Reputation: 44813

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.

You can use:

  • SingleLiveEvent: Send the event to only 1 observer, check here and here or alternatives here
  • LiveEvent: Send the event to all the observers, check here

Both of those approaches will not cache events, which means that an observer should be already observing the *LiveEvent to receive it

You can find articles online about alternative approaches but the philosophy behind them is probably the same

Upvotes: 1

Related Questions