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:


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.