I have 2 Activity
viz
- List
Activity
- 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