Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion: Use ViewModel for Android platform #1

Open
phillwiggins opened this issue Oct 24, 2021 · 4 comments
Open

Suggestion: Use ViewModel for Android platform #1

phillwiggins opened this issue Oct 24, 2021 · 4 comments

Comments

@phillwiggins
Copy link

phillwiggins commented Oct 24, 2021

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
Copy link
Author

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

@charlee-dev
Copy link

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
Copy link
Author

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

@phillwiggins
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants