19

I'm trying to follow the android documentation to implement Transformations in my project but I run into this problem Unresolved reference: Transformations. I don't know why my project can't see the Transformations class.

I'm using Kotlin version 1.5.21' and here is my code

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
    }
}

Any guidance is really appreciated.

user3765730
  • 223
  • 2
  • 7

3 Answers3

55

From lifecycle version 2.6.0 instead of using Transformations, you need to use the extension function directly myLiveData.switchMap or myLiveData.map (source)

siergiejjdw
  • 601
  • 5
  • 7
5

If there is a Class of PageViewModel like this

class PageViewModel : ViewModel() {

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


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

The new version can be like this:

class PageViewModel : ViewModel() {

    private val _index = MutableLiveData<Int>()

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


    fun setIndex(index: Int) {
        _index.value = index
    }
}
Mori
  • 2,653
  • 18
  • 24
2

Make sure to import

import androidx.lifecycle.Transformations

If the import gives an Unresolved reference error, add the following dependency to your build.gradle file

dependencies {
    ...
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.4.1"
}
danartillaga
  • 1,349
  • 1
  • 8
  • 19