Hello, Is there any official guideline to share vi...
# multiplatform
m
Hello, Is there any official guideline to share viewModel between android and ios in KMM?
m
Not sure what's considered official these days but this article from @John O'Reilly is a nice read!
m
Thank you a lot 😄
a
You can also check https://github.com/arkivanov/Decompose, this library allows shared VMs, as well as navigation.
e
Does anyone have the experience to compare the two libraries. And any opinions on this?
a
I'm not familiar with KMM-ViewModel, but I can say something about the "obsolete ViewModels" article. It uses Essenty library and it seems that the implementation could be much simpler, given the navigation is not covered in the article. E.g. one can create a shared ViewModel using Essenty library as follows:
Copy code
// commonMain

class MyViewModel : InstanceKeeper.Instance {

    override fun onDestroy() {
        // Dispose things here
    }
}
Using in Android:
Copy code
class MainActivity : AppCompatActivity() {

    private val instanceKeeper by lazy { instanceKeeper() }

    private val viewModel by lazy {
        instanceKeeper.getOrCreate(::MyViewModel)
    }
}
Using in other platforms would be close to the following:
Copy code
fun main() {
    val viewModel = MyViewModel()
    
    // At some point later
    viewModel.onDestroy()
}