Reputation: 373
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.
Upvotes: 32
Views: 13868
Reputation: 4651
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
}
}
Upvotes: 15
Reputation: 986
From lifecycle version 2.6.0 instead of using Transformations
, you need to use the extension function directly myLiveData.switchMap
or myLiveData.map
(source)
Upvotes: 81
Reputation: 1955
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"
}
Upvotes: 1