1

What exactly is this code doing?

private val supervisorJob = SupervisorJob()
protected val presenterScope = CoroutineScope(Dispatchers.Main + supervisorJob)

What is the result of Dispatchers.Main + supervisorJob? I understand it must be some sort of composition but how does it work? And how is it called? Thank you

1 Answer 1

5

That's a lot of questions.

What exactly is this code doing?

You can look at this as follows: this code creates a new CoroutineScope, with dispatcher set to Main and and behaviour set to SupervisorJob

Dispatchers.Main means that the coroutine will execute on the main thread. Usually this refers to Android UI thread.

SupervisorJob means that unlike regular Job behaviour, when failure of one of the children will also fail the parent, and all the other children too, the job will just continue as usual.

What is the result of Dispatchers.Main + supervisorJob?

The result is CoroutineContext. You can think of it as a hash map of different keyed values.

I understand it must be some sort of composition but how does it work?

You are correct. If you look at CoroutineContext implementation, you'll see that it implements operator fun plus, which allows to use + to combine two objects of type CoroutineContext

And how is it called?

Usually coroutine methods are extension methods on CoroutineScope. If we look at async(), for example:

public fun <T> CoroutineScope.async(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> T
): Deferred<T>
0

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