Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about coroutines scope constructor syntax

Tags:

kotlin

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?

like image 564
ktvktv Avatar asked Mar 13 '26 12:03

ktvktv


1 Answers

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.

like image 103
Rene Avatar answered Mar 15 '26 05:03

Rene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!