Junior — Middle
How can you ensure the preservation of an object associated with an active component in Koin?
sobes.tech AI
Answer from AI
In Koin, to save an object associated with an active component (such as an Activity or Fragment), a scope bound to the component's lifecycle is used.
To ensure the object is preserved for the lifetime of the component, you need to:
- Create a scope associated with the component.
- Define dependencies within this scope.
- Use the scope to obtain instances that will live as long as the component.
Example for Activity:
val activityModule = module {
scope<Activity> {
scoped { MyScopedDependency() }
}
}
// In Activity
class MyActivity : AppCompatActivity() {
private val myDependency: MyScopedDependency by currentScope.inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ...
}
}
Thus, the object MyScopedDependency will be created and preserved within the lifecycle of MyActivity and destroyed along with it.