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:
ArticleDaois provided by the abstractAppDatabaseclass- The
AppDatabaseclass is provided bygetRoomDatabase()function - The
getRoomDatabase()function takes theRoomDatabase.Builder<AppDatabase>as an argument - And finally the
RoomDatabase.Builder<AppDatabase>is provided by our platform-specificgetAndroidDatabaseBuilder()andgetIOSDatabaseBuilder()functions.
So to provide our ArticleDao - we need to build everything in reverse order.
- Check out branch
s4_room_start. The solution is ons4_room_solutionin case you need it. - Implement
databaseModulein ourcommonMain/diAppModule.ktfile. - From the
databaseModuleprovide a singletonArticleDaoby using ourgetRoomDatabase()function and then invoking an.articleDao()function on it. ThearticleDao()function is automatically generated byRoomat compile-time.
Tip: Start from point 4 above and build everything in reverse order.
0 comments