Reputation: 1378
When my application starts I create object with some data and I want to share the same instance of object between services/viewModels.
Is it possible to inject the same instance of data class to viewModel using Koin?
Edit:
I create user object in MainViewModel
when app loaded data from firebase at start.
@IgnoreExtraProperties
@Keep
data class User(
val id: String = "",
val name: String? = null,
val surname: String? = null,
val email: String? = null,
val avatarUrl: String? = null
)
Upvotes: 0
Views: 2275
Reputation: 2244
If your view model inherits from KoinComponent
, you can access getKoin
method to declare your user object.
class MainViewModel : ViewModel(), KoinComponent {
The user object will be available to rest of your application after declaration.
// user created from data from firebase ...
fun insertKoinFor(user: User) {
// declare koin the user of type User
getKoin().declare<User>(user)
// or declare with a named qualifier
getKoin().declare(user, named("myUser"))
}
Hope, it helps.
Upvotes: 1
Reputation: 152787
I would create a holder object, say UserManager
, to hold an optional User
instance. This holder is something you can provide in your koin graph as single
, and whatever component responsible setting up the User
instance (for example your MainViewModel
) can update the instance inside the singleton holder.
Upvotes: 1