我正在尝试在 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()
}
}
}
但我得到
Property must be initialized or be abstract
关于分配 weather
在 init
功能。我假设是这种情况,因为我正在使用协程
viewModelScope.launch
.override suspend fun getWeather(): LiveData<Weather> {
return withContext(IO){
initWeatherData()
return@withContext weatherDao.getWeather()
}
}
我该如何解决?
最佳答案
您可以声明weather
属性为 lateinit
:
private lateinit var weather: LiveData<String>
或使其成为 nullable :
private var weather: LiveData<String>? = null
如果您确定在首次使用该属性之前会对其进行初始化,请使用
lateinit
否则让它 可以为空 .
关于android - LiveData 和 Coroutines - 属性必须被初始化或抽象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55713969/