Step #7: Adding a Store to the Repository
Next, we need to have our ToDoRepository
get access to a ToDoEntity.Store
, so it can manipulate the database instead of an in-memory transient copy of data.
Update the ToDoRepository
to add a pair of constructor parameters:
class ToDoRepository(
private val store: ToDoEntity.Store,
private val appScope: CoroutineScope
) {
The first parameter is our DAO, ToDoEntity.Store
. We will use that to work with the database. The second parameter is a CoroutineScope
. Take it on faith for the moment that we need that parameter — we will apply it in the next section and see more about why we need it in the next tutorial.
Next, in ToDoApp
, add this single
to our koinModule
:
single(named("appScope")) { CoroutineScope(SupervisorJob()) }
This sets up a singleton instance of a CoroutineScope
, wrapped around a SupervisorJob
. That will be important when we tie in our viewmodels to our updated repository, as we will see in the next tutorial.
The named("appScope")
parameter to the single()
call tells Koin that there might be more than one CoroutineScope
in our module, and we only want to use this CoroutineScope
if somebody asks for it by name. In reality, we will only have this one CoroutineScope
, but using named components like this is good practice for a general-purpose object like CoroutineScope
.
Then, in ToDoApp
, change the ToDoRepository
line in koinModule
to be:
single {
ToDoRepository(
get<ToDoDatabase>().todoStore(),
get(named("appScope"))
)
}
We use get()
twice to find our dependencies and inject them. However, the get()
calls are a bit different than the ones we have used previously:
- The first one uses generics to indicate that we want to fetch a
ToDoDatabase
. Normally,get()
works on the type of the parameter, but that is aToDoEntity.Store
. Koin does not know how to get such a thing, so we tell it toget()
theToDoDatabase
, and from there we calltodoStore()
ourselves to get theToDoEntity.Store
thatToDoRepository
needs. - The second one uses a similar
named("appScope")
parameter to the one we used in theCoroutineScope
single
declaration. So, we are asking toget()
the object of the desired type (CoroutineScope
, based on the parameter type) that is namedappScope
.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.