未解决的引用: Transformations

22

我正在尝试按照Android文档在我的项目中实现Transformations,但是我遇到了这个问题:未解决的引用: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
    }
}

非常感谢您的指导。

3个回答

62

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


6
这应该被标记为正确答案,因为降级到以前的版本不是一个好的选择。 - Abraão Caldas
如何以相同的方式使用switchMap或map? - undefined

8
如果有一个类似这样的 PageViewModel 类
class PageViewModel : ViewModel() {

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


    fun setIndex(index: Int) {
        _index.value = index
    }
}

新版本可以是这样的:

class PageViewModel : ViewModel() {

    private val _index = MutableLiveData<Int>()

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


    fun setIndex(index: Int) {
        _index.value = index
    }
}

2

请确保导入

import androidx.lifecycle.Transformations

如果导入时出现“未解决的引用”错误,请将以下依赖项添加到您的build.gradle文件中。
dependencies {
    ...
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.4.1"
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接