· 2 min read Posted by Kevin Schildhorn

Android Jetpack ViewModel has KMP Support!

This article discusses the newest version of the lifecycle-viewmodel artifact, part of the official Android Jetpack library, and how it adds support for KMP projects.

ViewModel Support for KMP

As of version 2.8.0-alpha03 the lifecycle-* artifacts now support Kotlin Multiplatform! This means classes such as ViewModel, ViewModelStore, ViewModelStoreOwner and ViewModelProvider can now be used in your common code.

This is especially exciting for the ViewModel class, as in the past you’ve always needed an abstraction or expect/actual class to share your ViewModel logic. Originally this artifact was only available for Android targets, but now with official support you can define and reference a ViewModel from your common code! The ViewModel acts as you would expect, and includes the viewModelScope which is a CoroutineScope that allows you to easily run coroutines from ViewModel.

Testing it yourself

In order to test this update simply add the implementation to your common dependencies:

sourceSets {
    commonMain {
        dependencies {
            implementation("androidx.lifecycle:lifecycle-viewmodel:2.8.0-alpha03")
        }
    }
}

One thing worth noting adding this new version is that there can be conflicts. Since Jetpack Compose includes the ViewModel as well, you may get an error about a duplicate class when running.

>Duplicate class androidx.lifecycle.ViewModelKt found in modules lifecycle-viewmodel-ktx-2.6.1-runtime (androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.1) and lifecycle-viewmodel-release-runtime (androidx.lifecycle:lifecycle-viewmodel-android:2.8.0-alpha03)

To get around this issue, you can exclude the view model dependency from libraries that depends on it:

implementation("androidx.activity:activity-compose") {
    exclude(group = "androidx.lifecycle", module = "lifecycle-viewmodel-ktx") // Here we are exlcuding the ViewModel dependency
}

After this it should be smooth sailing! You can now use a common ViewModel in your multiplatform project.

Touchlab will be doing some experiments with the new library, and may post samples in the future. To see an example project that already has the ViewModel integrated, check out John O’Reilly’s Fantasy Premier League.

joreilly/FantasyPremierLeague