5.6 (Exercise) - Injecting platform-specific dependencies. Room

Any app that wants to have a good user experience should not have “empty” screens whenever something is loading on its main page. In case our app encounters an error when loading articles from our API (like in the case when there is no network connection)- I want you to display articles that were previously cached in the database.

We’re learning Koin here - so the Room functionality and the logic for displaying articles has been implemented for you already. Your job is to wire up the dependencies with Koin to make it work.

The starting code for this exercise is on s4_room_start branch. The solution is on s4_room_solution branch.

We do the saving and retrieving from Room in our NewsRepositoryImplvia the articleDao

class NewsRepositoryImpl(
    private val httpClient: HttpClient,
    private val articleDao: ArticleDao
) : NewsRepository {

Your job is to provide a singleton ArticleDao from our di directory

If we go down the “rabbit hole” of dependencies, you will see that:

  1. ArticleDao is provided by the abstract AppDatabase class
  2. The AppDatabase class is provided by getRoomDatabase() function
  3. The getRoomDatabase() function takes the RoomDatabase.Builder<AppDatabase> as an argument
  4. And finally the RoomDatabase.Builder<AppDatabase>is provided by our platform-specific getAndroidDatabaseBuilder() and getIOSDatabaseBuilder() functions.

So to provide our ArticleDao - we need to build everything in reverse order.

  1. Check out branch s4_room_start . The solution is on s4_room_solution in case you need it.
  2. Implement databaseModule in our commonMain/di AppModule.kt file.
  3. From the databaseModule provide a singleton ArticleDao by using our getRoomDatabase() function and then invoking an .articleDao() function on it. The articleDao() function is automatically generated by Room at compile-time.

Tip: Start from point 4 above and build everything in reverse order.

Complete and Continue  
Discussion

0 comments