dev90
dev90

Reputation: 7529

Can we add multiple ViewModel.observer() method in a single activity

I have an activity that performs multiple background tasks, for example:

getJWTToken(), sendFCMTokenToServer(), isPromoAvailable(), isForcedUpgradeRequired(), fetchNewsFromServer(), sendUserLatLngToServer()

These all are network calls, and take some time.

This is what i have done for 1 method.

HomeViewModel homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class); 


    homeViewModel.sendFCMTokenToServer().observe(this, isFCMSendToServer -> {
       Toast.makeText(this, "Home FCM Observer called", Toast.LENGTH_SHORT).show();
     });

Now my question is do i need to repeat the above line homeViewModel.observer(this, ) for each method, or there is some other way for achieving this.

Upvotes: 1

Views: 2014

Answers (1)

Jay Patel
Jay Patel

Reputation: 516

I think, You should not!

You don't need to observe these changes separately.

You can do these:

  • make ViewState Data model class which contains all these data (jwt token, other booleans and all)

  • observe ViewModel based on this model from activity.

  • In ViewModel, you can just change/update these ViewState model values using LiveData.postValue() as well.

Upvotes: 1

Related Questions