doublesymmetry / multiplatform-viewmodel

Shared ViewModel in Kotlin Multiplatform

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

multiplatform-viewmodel 🗳

Create shared ViewModel's for shared business logic using our ViewModel base class.

Features

  • Uses Jetpack ViewModel on Android for lifecycled
  • Exposes a CoroutineScope to be used in your methods

Overview of Package

This package has 1 component to it: A ViewModel class you can base your view models on.

Getting Started

Add Dependency

commonMain {
    dependencies {
        // ...
        api("com.doublesymmetry:multiplatform-viewmodel:0.0.1")
    }
}

Expose it to iOS native side

ios {
    binaries {
        framework {
            baseName = "shared"
            export(Deps.viewmodel) // required to expose the class to iOS
        }
    }
}

Using the ViewModel

class ExampleViewModel: ViewModel() {
    private val _viewState = MutableStateFlow(UIViewState())
    val viewState: StateFlow<UIViewState> = _viewState
 
    fun onLaunched() {
        scope.launch {
            // fetch some data
            _viewState.emit(newState)
        }
    }
}

Using your ViewModel on iOS with a UIViewController

When using it on iOS you'll want to make sure that you call clear() on your ViewModel on deinit to properly kill the CoroutineScope

About

Shared ViewModel in Kotlin Multiplatform

License:Apache License 2.0


Languages

Language:Kotlin 100.0%