【发布时间】:2019-09-06 21:34:10
【问题描述】:
我正在尝试在 MVVM 中同时使用 LiveData 和 Coroutines,我可能会遗漏一些简单的东西。
class WeatherViewModel (
private val weatherRepository: ForecastRepository
) : ViewModel() {
var weather: LiveData<Weather>;
/**
* Cancel all coroutines when the ViewModel is cleared.
*/
@ExperimentalCoroutinesApi
override fun onCleared() {
super.onCleared()
viewModelScope.cancel()
}
init {
viewModelScope.launch {
weather = weatherRepository.getWeather()
}
}
}
但是我在init 函数中分配weather 时得到Property must be initialized or be abstract。
我假设是这种情况,因为我正在使用协程viewModelScope.launch。
override suspend fun getWeather(): LiveData<Weather> {
return withContext(IO){
initWeatherData()
return@withContext weatherDao.getWeather()
}
}
我该如何解决这个问题?
【问题讨论】:
标签: android kotlin kotlin-coroutines android-livedata coroutine