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

标签 android kotlin kotlin-coroutines android-livedata coroutine

我正在尝试在 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关于分配 weatherinit功能。
我假设是这种情况,因为我正在使用协程 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/

相关文章:

java - 在 Android App 中编译 Latex 文档

kotlin - 协程范围的构造函数中的协程上下文的Kotlin组成

android - 从蓝牙连接的 Android 应用程序控制 Arduino 上的 LED 的问题

java - 如何将 Dokka 添加到 Android 项目而不需要在依赖项部分添加额外的类路径?

android - Xamarin 是否支持 Xamarin Android 绑定(bind)库中的 Kotlin 协程?

kotlin - 为什么协程首先在调用者线程上运行,但在第一个挂起点之后它在 “Dispatchers.Unconfined” 中的 DefaultExecutor 上运行?

android - 打开 .xml 文件后 Eclipse 崩溃

android - Google Maps API V2 'Failed to Load Map. Could not contact Google Servers',即使我检查权限和 keystore

android - 如何从另一个 Activity 访问在一个 Activity 中创建的数据库?

unit-testing - 使用协程进行测试时检测到使用不同的调度程序