androidandroid-livedataandroid-livedata-transformations

Unresolved reference: Transformations after upgrading lifecycle dependency


After upgrading the lifecycle dependency from 2.6.0-alpha04 to 2.6.0-beta01 I got Unresolved reference: Transformations and it can't import androidx.lifecycle.Transformations class.

import androidx.lifecycle.Transformations
...
var myList: LiveData<List<Bookmark>> = Transformations.switchMap(
            bookMarkType
        ) { input: Int? ->
            when (input) {
                ARTICLE_BOOKMARK -> return@switchMap repository.articleBookmarks
                WEBSITE_BOOKMARK -> return@switchMap repository.websiteBookmarks
                LINK_BOOKMARK -> return@switchMap repository.linkBookmarks
            }
            repository.websiteBookmarks
        }

Solution

  • As of 2.6.0-alpha05 version:

    Transformations is now written in Kotlin. This is a source incompatible change for those classes written in Kotlin that were directly using syntax such as Transformations.map - Kotlin code must now use the Kotlin extension method syntax that was previously only available when using lifecycle-livedata-ktx. When using the Java programming language, the versions of these methods that take an androidx.arch.core.util.Function method are deprecated and replaced with the versions that take a Kotlin Function1.

    So, instead of using Transformations, you need to use the extension function directly myLiveData.switchMap or myLiveData.map

    So, to fix this use:

    var myList: LiveData<List<Bookmark>> = bookMarkType.switchMap { input: Int? ->
                when (input) {
                    ARTICLE_BOOKMARK -> return@switchMap repository.articleBookmarks
                    WEBSITE_BOOKMARK -> return@switchMap repository.websiteBookmarks
                    LINK_BOOKMARK -> return@switchMap repository.linkBookmarks
                }
                repository.websiteBookmarks
            }