3

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?

1 Answer 1

5

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.