源代码可以在: https:/github.comAli-RezaeiTVMaze。
我有以下的存储库类.我知道Room不支持MutableLiveData,而是支持LiveData。
class ShowRepository(
private val showDao: ShowDao,
private val api: TVMazeService
) {
/**
* A list of shows that can be shown on the screen.
*/
val shows: LiveData<List<Show>> =
Transformations.map(showDao.getShows()) {
it.asDomainModel()
}
/**
* Refresh the shows stored in the offline cache.
*/
suspend fun refreshShows(): Result<List<Show>> = withContext(Dispatchers.IO) {
try {
val news = api.fetchShowList().await()
showDao.insertAll(*news.asDatabaseModel())
Result.Success(news)
} catch (err: HttpException) {
Result.Error(err)
}
}
}
据我所知,Room不支持MutableLiveData,而是支持LiveData。所以我在我的ViewModel中创建了两个对象来观察。
class MainViewModel(
private val repository: ShowRepository,
app: Application
) : AndroidViewModel(app) {
private val _shows = repository.shows
val shows: LiveData<List<Show>>
get() = _shows
private val _liveData = MutableLiveData<Result<List<Show>>>()
val liveData: LiveData<Result<List<Show>>>
get() = _liveData
/**
* init{} is called immediately when this ViewModel is created.
*/
init {
if (isNetworkAvailable(app)) {
viewModelScope.launch {
_liveData.postValue(repository.refreshShows())
}
}
}
}
我使用 show
LiveData varialbe提交到我的Activity列表中。
viewModel.shows.observe(this, Observer { shows ->
viewModelAdapter.submitList(shows)
})
而我使用 LiveData
变量,以便在发生异常时显示错误信息。refreshShows()
仓库的。
viewModel.liveData.observe(this, Observer { result ->
if (result is Result.Error) {
Toast.makeText(this, getString(R.string.failed_loading_msg), Toast.LENGTH_LONG).show()
Timber.e(result.exception)
}
})
你认为有没有更好的解决方案,在ViewModel中使用一个LiveData而不是两个?
我想你可以改进你的代码,使用这个方法 回购 作为基础。它使用livedata的单源真实策略。我想你必须要挖一下repo才能理解这段代码,但总的来说,这段代码会从api上获取数据,存储在ur房间里,并作为结果提供ur房间查询的anwer,所以观察这个就可以了。