android / architecture-samples

A collection of samples to discuss and showcase different architectural tools and patterns for Android apps.
Apache License 2.0
44.37k stars 11.62k forks source link

[dev-hilt] Dispatchers.IO is singletone (Or in dependency graph)? #763

Open ArsalImam opened 4 years ago

ArsalImam commented 4 years ago

I was checking the template implementation of Hilt(DI), but I am not sure why do we need to define Dispatchers.IO in dependency graph (if require, then why singleton?) as it is already a JVMStatic by default in kotlinx.coroutines packages.

Branch: dev-hilt Implementation Reference: click here

kursivee commented 3 years ago

This helps out with unit testing classes that use Dispatchers.IO. The MainCoroutineRule only allows you to set the main dispatcher as far as I'm aware. https://github.com/android/architecture-samples/blob/a6156ad6bb0888aa60bdd587a888679ab2c64e50/app/src/sharedTest/java/com/example/android/architecture/blueprints/todoapp/MainCoroutineRule.kt#L57 I don't think there's anything that supports something like Dispatchers.setIO.

The current solution is to inject the dispatcher like in the DefaultTaskRepository https://github.com/android/architecture-samples/blob/a6156ad6bb0888aa60bdd587a888679ab2c64e50/app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/source/DefaultTasksRepository.kt#L35 Then provide Dispatcher.Main in the unit test so now it's controlled by the MainCoroutineRule https://github.com/android/architecture-samples/blob/a6156ad6bb0888aa60bdd587a888679ab2c64e50/app/src/test/java/com/example/android/architecture/blueprints/todoapp/data/source/DefaultTasksRepositoryTest.kt#L61

Talk in 2019 Dev Summit on this topic