Search code examples
androidandroid-roomandroid-architecture-componentsandroid-livedata

LiveData not updating data from one Activity to another Activity - Android


I have 2 Activity viz

  1. List Activity
  2. Detail Activity

The list Activity shows list of items and detail Activity is shown on clicking an item from the list. In the ListActivity we observe for fetching the feeds from the DB and once we do, we update the UI.

List page

feedViewModel.getFeeds().observe(this, Observer { feeds ->
      feeds?.apply {
            feedAdapter.swap(feeds)
            feedAdapter.notifyDataSetChanged()
      }
})

Now we have a DetailActivity page which updates the feed (item) and Activity is finished but the changes are not reflected in the ListActivity.

Details page

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        feedViewModel.setFeedId(id)
        feedViewModel.updateFeed()
}

Feed View Model

class FeedViewModel(application: Application) : AndroidViewModel(application) {


    private val feedRepository = FeedRepository(FeedService.create(getToken(getApplication())),
            DatabaseCreator(application).database.feedDao())

    /**
     * Holds the id of the feed
     */
    private val feedId: MutableLiveData<Long> = MutableLiveData()

    /**
     * Complete list of feeds
     */
    private var feeds: LiveData<Resource<List<Feed>>> = MutableLiveData()

    /**
     * Particular feed based upon the live feed id
     */
    private var feed: LiveData<Resource<Feed>>

    init {
        feeds = feedRepository.feeds
        feed = Transformations.switchMap(feedId) { id ->
            feedRepository.getFeed(id)
        }
    }

    /**
     * Get list of feeds
     */
    fun getFeeds() = feeds

    fun setFeedId(id: Long) {
        feedId.value = id
    }

    /**
     * Update the feed
     */
    fun updateFeed() {
        feedRepository.updateFeed()
    }

    /**
     * Get feed based upon the feed id
     */
    fun getFeed(): LiveData<Resource<Feed>> {
        return feed
    }

}

For simplicity purpose some code has been abstracted. If required I can add them to trace the problem


Solution

  • After lots of investigation and some idea from this answer from another question. I figured out the issue.

    Issue

    The DatabaseCreator(application).database.feedDao() was not creating singleton instance of the database due to which the first Activity had another instance where LiveData was listening for changes and 2nd Activity had another instance where after updating the data the callback was ignored.

    Solution

    Use Dagger or any other dependency injection to insure only single instance of DB and DAO is created.