daniaviladomingo / kmm

Rick & Morty Kotlin/Compose Multiplatform: Ktor, Sqldelight, Koin, Flow, MVI, Compose
178 stars 15 forks source link

Suggestion: Use ViewModel for Android platform #1

Open phillwiggins opened 3 years ago

phillwiggins commented 3 years ago

Hey,

I really like what you have done here. I'm new to KMM and have taken some inspiration from this project. Unless I'm misunderstanding a few things (Never used Koin before), this shared "BaseViewModel" doesn't survive config changes. I.e. it's making network requests upon rotation, lanugage changes and light/dark mode.

I had a little play with it and managed to let it survive config changes by introduction Android ViewModel on the android platform side by adding:

expect open class OSViewModel() in commonMain `import androidx.lifecycle.ViewModel

actual open class OSViewModel : ViewModel() in androidMain

actual open class OSViewModel in iOSMain

androidx.lifecycle:lifecycle-viewmodel-ktx depedency in the build.gradle.kts::shared androidMain

private val vm: HomeViewModel by viewModels() in the activities instead of Koin inject()

abstract class MainIoExecutor : OSViewModel() in commonMain IOExecutor

By doing this, the Viewmodel is still shared, but on the Android platform, it takes the logic of the Android ViewModel to survive config changes. Again, this might not be necessary as I have misunderstood something but it seems to work nicely on my project.

phillwiggins commented 3 years ago

I still just need to test the logic of coroutines being cancelled at the correct time.

charlee-dev commented 2 years ago

the whole point of KMP is to do as much shared logic possible and less native code so not using Android ViewModel is very good approach in my opinion. Especially using MVi where all you do is emitting state and waiting for events,

phillwiggins commented 2 years ago

Technically, the VM is still shared. Except it survives config changes. It's a quick win by extending Android ViewModel on one platform.

phillwiggins commented 2 years ago

I think we're on a different page here. The VM logic would still exist and be shared. The only difference is the Android VM would survive config changes. The above code I proposed is the only change.