Home > Mobile >  ViewModel Observer not working when activity is backstacked
ViewModel Observer not working when activity is backstacked

Time:01-07

I have 2 activities:

A: for listing an array list,

B: for inserting on the array list.

A is observing the array list:

playlistItemsViewModel.playlistItems.observe(this, { playlistItems ->
        Log.i("Received playlistItems", playlistItems.size.toString())
        adapter = PlaylistItemAdapter(playlistItems)
        binding.rvPlaylistItems.adapter = adapter
})

A is also observing when a new item is added:

playlistItemsViewModel.newItem.observe(this, { newItem ->
       Log.i("newItem >>>", newItem.toString())
       adapter.addPlaylistItem(newItem)
})

To add a new item I start an intent B where playlistItemsViewModel.submitVideoItem(item) does its work, but the activity A is paused so it does not receive the posted value, when the back button is pressed and A is resumed, it still does not receive anything.

When playlistItemsViewModel.submitVideoItem(item) works inside A, the MutableLiveData newItem postValue posts successfully. Basically, when you add a new playlist item in activity B it is inserted on the activity A that is paused back on the stack.

What am I missing?

CodePudding user response:

I am understanding when Activity B inserts a new value for the variable newItem then when returning to Activity A you want to update it.

If it were me I would use startActivityForResult() and onActivityResult() this would be more appropriate.

https://developer.android.com/training/basics/intents/result

As for LiveData, you can read it here to better understand the problem you are having.

https://developer.android.com/topic/libraries/architecture/livedata

CodePudding user response:

You can not share a same instance of ViewModel between Activities you can only share viewmodel between Fragments and that too by an Activity's Context . (You can confirm this by printing the viewmodel Object in Logs in A and B, you will get 2 instances)

The problem here is your Activities A and B holding a different instances of ViewModel so it will never work .

For a Solution you can switch to Fragments or if its too much for you then can go for ActivityResultApi.

  •  Tags:  
  • Related