Coroutines Best Practices Flashcards
How should I use dispatcher in classes?
Don't hardcode dispatcher in the class rather we should inject it in the constructor. Benefits- It will make unit and instrumentation testing easier.
Which layer should create coroutines in Android app?
The ViewModel/Presenter layer should create coroutines.
Benefits- The UI layer should be dumb and not directly trigger any business logic.
Instead, it should defer that responsibility to the ViewModel/Presenter layer. Testing the UI layer requires instrumentation tests in Android which needs an emulator to run.
Where should suspend functions create in Android project?
The layer below the ViewModel/Presenter should expose suspend functions and Flows.
Benefits- The caller generally the viewmodel layer can control the execution and lifecycle of the work happening in those layers, being able to cancel when needed.
How to execute coroutines during the lifetime of application?
Create a scope in Application class of Android.
class MyApplication : Application() { // No need to cancel this scope as it'll be torn down with the process val applicationScope = CoroutineScope(SupervisorJob() + otherConfig) }