I don't understand the syntax for coroutines constructor.
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
I know the parameter need Coroutine Context class. What I don't understand is how can we add 2 different object? Dispatchers.Main class is MainCoroutineDispatcher and viewModelJob class is Job. Is there any explanation about it?
CoroutineScope is not a constructor but a function, defined as:
public fun CoroutineScope(context: CoroutineContext): CoroutineScope = ...
The parameter is the interface CoroutineContext which itself defines a plus operator:
public operator fun plus(context: CoroutineContext): CoroutineContext = ...
The plus operator returns another CoroutineContext. Dispatchers.Main and Job implement the interface CoroutineContext.
That said, Dispatchers.Main + viewModelJob is the invocation of plus that constructs another CoroutineContext. Internal this results in a collection of the both instances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With