Jetpack ViewModel has a lot of advantages, it's a ...
# koin
m
Jetpack ViewModel has a lot of advantages, it's a good state holder because it's aware of the configuration changes and other stuff. Suppose that you have another class, that is not a viewModel, and you want the same behavior. Is it posible using koin? When you're injecting a VM, you are injecting something that has a lifecycle aware scope, so is it possible?
a
viewModel
definition can be used inside a scope. It would allow you to reuse the same
scoped
definition yes 👌
m
I'm a bit confused, the idea is to create another class that is not a view model, but it should have the same scope as the view model. Using view model:
Copy code
class CustomViewModel : ViewModel()

val module = module {
    viewModel { CustomViewModel() }
}

@Composable
fun ViewModelComposable() {
    val viewModelInstance = getViewModel<CustomViewModel>()
}
Using custom class:
Copy code
class Foo

val module2 = module {
    scope<> { // Not sure about the scope
        scoped { Foo() }
    }
}

@Composable
fun FooComposable() {
    val foo = getKoin().get<Foo>()
}
So, what I need is that
foo
has the same behavior as
viewModelInstance
, they should have the same scope. BTW: Keep in mind, that
viewModel { ... }
definition can be used only if you extend a Jetpack View Model. In my use case, I'm using Kotlin Multiplatform, I'm defining the view model in my shared module (Foo), and it cannot extend Jetpack's ViewModel. However, when I'm inject it from android, I need the same behavior as a Jetpack's ViewModel
@arnaud.giuliani Thanks for your response! I'm pinging you because you may lost the thread. Can you clarify your response please?
a
perhaps take a look at this article, it take a tour on Scopes https://proandroiddev.com/understanding-android-scopes-with-koin-cfe6b60ca579
In my use case, I’m using Kotlin Multiplatform, I’m defining the view model in my shared module (Foo), and it cannot extend Jetpack’s ViewModel. However, when I’m inject it from android, I need the same behavior as a Jetpack’s ViewModel
then in your case you can’t benefit from Android Scopes. You have to create/destroy scopes by hand, at the start and at the end of your main component
m
Cool, I'll take a look at it! Thanks!
👍 1