Koin: How to handle scope?

Sree Kumar A.V
2 min readNov 4, 2019

--

Most of the time we end up in a place where you need a dependency only for a specific duration of time.

By default in Koin, we have 3 kinds of scopes:

  • single definition, create an object that persistent with the entire container lifetime (Similar to Singleton).
  • factory definition, create a new object each time. No persistence in the container (can’t be shared).
  • scoped definition, create an object that persistent tied to the associated scope lifetime.

In Android, if you look at ViewModel, it can be scoped to Activity and shared across the different Fragments hosting under the same Activity.

If you need a component that is scoped to multiple activities, how do you do that?

One solution will be, having a singleton class hold the components and clear them manually when you no longer need them. This solution is not a clean solution!!. This will be a pain, when you have to create multiple dependence, then clear them, when no longer needed. If you create a scoped components, the dependency coming from the same scope can be cleared using scope.close()

val appModule = module {

scope(named("session")) {
scoped { Session() }
}

single<SessionRepository> {
val scope = getKoin().getOrCreateScope(
"sessionID", named("session"))
val session = scope.getScope("sessionID").get<Session>()
SessionRepositoryImpl(session)
}
single { SessionPresenter(get()) }
}

Before accessing the scope, scope needs to be created.

val scope = getKoin().getOrCreateScope(
"sessionID", named("session"))

All the dependencies under the same scope can be accessed by

val session = scope.getScope("sessionID").get<Session>()

Now clearing the scope can be done through.

val scope = getKoin().getScope("sessionID")
scope.close()

Scoped dependencies can be created dynamically also.

val scope = getKoin().getScope("sessionID")
scope.declare(Session())

Attaching source code here.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sree Kumar A.V
Sree Kumar A.V

Written by Sree Kumar A.V

Lead Android Software Engineer @ YML

No responses yet

Write a response