I've been trying to implement a custom scope in kodein for the past day and I am about to rip my hair off. My application is built on 2 activities, one activity for login, the other when the user is logged in (I'll call it MainActivity). I have several singleton services that fetches data from a Firestore database that I use within many fragments inside my MainActivity, and I am currently using Kodein for getting my singleton objects of each service.
Summary of my Service:
class TagsService(context: Context): KodeinAware {
override val kodein by closestKodein(context)
val tags: MutableLiveData<ArrayList<Tag>> = MutableLiveData(ArrayList())
// Other stuff fetching data and storing it in tags
}
And the service inside my Kodein application
bind() from singleton { TagsService(applicationContext) }
Inside my fragment I simply fetch my tagsService class with
private val tagsService: TagsService by instance()
The problem now is that when the user signs out, I have to clean up all tags in this case, wait for the user to get logged in, create a new query etc etc, a lot of work. But if this service could somehow be "killed" and then started up again when the user logged in (comes back to MainActivity, also without saving its last state, just a new object) everything would be cleaned up automatically, without me having to write a lot of code.
Goal: Since MainActivity only is "active" when the user is logged in and properly authenticated I would like to attach a lifecycle to my TagsService object, whenever MainActivity dies it also kills my tagsService and then "re-initializes" whenever MainActivity "lives" again.
I am terribly sorry if its hard to grasp what I'm trying to do, I'm quite new to kotlin and programming as a whole
To reach this you could Kodein-DI scopes (https://docs.kodein.org/kodein-di/7.3/core/using-environment.html#scope).
You bind your service like:
bind() from scoped(ActivityScope).singleton { TagsService(applicationContext) }
where ActivityScope
is either a scope that you create, a WeakContextScope.of<Activity>()
, or an already bundle scope in the Android module of Kodein-DI (https://docs.kodein.org/kodein-di/7.3/framework/android.html).
Thus, you can inject your service with:
private val tagsService: TagsService by on(activityReference).instance()