LiveData 和 Coroutines - 属性必须被初始化或抽象

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 。 weatherinitviewModelScope.launch

override suspend fun getWeather(): LiveData<Weather> {
    return withContext(IO){
       initWeatherData()
       return@withContext weatherDao.getWeather()
    }
}
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

Luc*_*tti 0

更改签名如下:

var weather =  MutableLiveData<Weather>();
Run Code Online (Sandbox Code Playgroud)

另外,您应该只返回一个Weather对象而不是 LiveData<>,因此您应该将 的签名更改getWeather()为 return : Weather