Coroutines Best Practices Flashcards

1
Q

How should I use dispatcher in classes?

A
Don't hardcode dispatcher in the class rather we should inject it in the constructor.
Benefits- It will make unit and instrumentation testing easier.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Which layer should create coroutines in Android app?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Where should suspend functions create in Android project?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to execute coroutines during the lifetime of application?

A

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)
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly