I created a multiplatform class for ViewModel in w...
# multiplatform
k
I created a multiplatform class for ViewModel in which android expect will extend
androidx.lifecycle.ViewModel
. But the problem was that i created these in
shared
module and when i used
shared
module in another module and created FeatureViewModel in commonMain, it is giving error of
Cannot access 'androidx.lifecycle.ViewModel' which is a supertype of 'FeatureViewModel'. Check your module classpath for missing or conflicting dependencies
. Why common code worrying about actual implementations?
Copy code
expect open class ViewModel() {

    protected val viewModelScope: CoroutineScope

    protected fun onCleared()
}
Copy code
actual open class ViewModel : AndroidViewModel() {

    actual val viewModelScope: CoroutineScope = AndroidViewModelScope

    actual override fun onCleared() {
        super.onCleared()
    }

}
When am adding androidx.viewModel dependency in androidMain it is working, but why i have to add that in every module which am using?
m
Use this approach, it's more flexible: commonMain:
Copy code
class ViewModel(
    val viewModelScope: CoroutineScope,
) {
    fun onCleared() {}
}
androidMain:
Copy code
class AndroidViewModel(): ViewModel() {
    val viewModel = ViewModel(viewModelScope = viewModelScope)

    override fun onCleared() {
        super.onCleared()
        viewModel.onCleared()
    }
}
Try to use expect/actual only with functions, most of the time it's not needed in classes, and it comes with some limitations. Instead, you can have an interface and a factory expect function that creates the implementation for that interface on each platform.