我有 2 个Activity
即
- 列表
Activity
- 细节
Activity
列表Activity
显示项目列表,Activity
单击列表中的项目会显示详细信息。在ListActivity
我们观察从数据库中获取提要的过程中,一旦我们这样做了,我们就会更新 UI。
列表页面
feedViewModel.getFeeds().observe(this, Observer { feeds ->
feeds?.apply {
feedAdapter.swap(feeds)
feedAdapter.notifyDataSetChanged()
}
})
现在我们有一个DetailActivity
更新提要(项目)并Activity
完成的页面,但更改未反映在ListActivity
.
详情页面
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
feedViewModel.setFeedId(id)
feedViewModel.updateFeed()
}
提要视图模型
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
}
}
为简单起见,一些代码已被抽象出来。如果需要,我可以添加它们以跟踪问题