I am trying to use LiveData and Coroutines together in MVVM, and I may be missing something simple.
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()
}
}
}
But I am getting Property must be initialized or be abstract on assigning the weather in the init function.
I am assuming this is the case because I am using coroutines viewModelScope.launch.
override suspend fun getWeather(): LiveData<Weather> {
return withContext(IO){
initWeatherData()
return@withContext weatherDao.getWeather()
}
}
How do I fix this?
You can declare weather property as lateinit:
private lateinit var weather: LiveData<String>
Or make it nullable:
private var weather: LiveData<String>? = null
If you're sure that the property will be initialized before you first use it use lateinit otherwise make it nullable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With