Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LiveData and Coroutines - Property must be initialized or abstract

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?

like image 961
Alan Avatar asked Nov 07 '22 18:11

Alan


1 Answers

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.

like image 147
Sergey Avatar answered Nov 15 '22 08:11

Sergey