Ala*_*lan 5 coroutine kotlin android-livedata kotlin-coroutines
我试图在 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()
}
}
}
Run Code Online (Sandbox Code Playgroud)
但我开始在函数中Property must be initialized or be abstract
分配。我假设是这种情况,因为我正在使用 coroutines 。 weather
init
viewModelScope.launch
override suspend fun getWeather(): LiveData<Weather> {
return withContext(IO){
initWeatherData()
return@withContext weatherDao.getWeather()
}
}
Run Code Online (Sandbox Code Playgroud)
我该如何解决?
更改签名如下:
var weather = MutableLiveData<Weather>();
Run Code Online (Sandbox Code Playgroud)
另外,您应该只返回一个Weather
对象而不是 LiveData<>,因此您应该将 的签名更改getWeather()
为 return : Weather
。
归档时间: |
|
查看次数: |
1391 次 |
最近记录: |