未解决的参考:转换

use*_*730 26 android transformation kotlin

我试图按照 android 文档在我的项目中实现 Transformations 但我遇到了这个问题Unresolved reference: Transformations。我不知道为什么我的项目看不到 Transformations 类。

我正在使用 Kotlin 版本 1.5.21',这是我的代码

class MyViewModel(private val repository: PostalCodeRepository) : ViewModel() {
    private val addressInput = MutableLiveData<String>()
    val postalCode: LiveData<String> = Transformations.switchMap(addressInput) {
            address -> repository.getPostCode(address) }


    private fun setInput(address: String) {
        addressInput.value = address
    }
}
Run Code Online (Sandbox Code Playgroud)

非常感谢任何指导。

小智 69

从生命周期版本2.6.0开始Transformations,您需要直接使用扩展函数myLiveData.switchMap,而不是使用myLiveData.map来源

  • 这应该标记为正确答案,因为降级到以前的版本不是一个好的途径。 (6认同)

Mor*_*ori 11

如果有一个这样的PageViewModel类

class PageViewModel : ViewModel() {

    private val _index = MutableLiveData<Int>()
   val text: LiveData<String> = Transformations.map(_index) {
        "$it"
   }


    fun setIndex(index: Int) {
        _index.value = index
    }
}
Run Code Online (Sandbox Code Playgroud)

新版本可以是这样的:

class PageViewModel : ViewModel() {

    private val _index = MutableLiveData<Int>()

    val text: LiveData<String> = _index.map { "$it" }


    fun setIndex(index: Int) {
        _index.value = index
    }
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*aga 2

确保导入

import androidx.lifecycle.Transformations
Run Code Online (Sandbox Code Playgroud)

如果导入出现Unresolved reference错误,请将以下依赖项添加到您的build.gradle文件中

dependencies {
    ...
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.4.1"
}
Run Code Online (Sandbox Code Playgroud)