there's a scope in Android with a description that...
# coroutines
m
there's a scope in Android with a description that says it's built with
MainCoroutineDispatcher.immediate
, and says:
`MainCoroutineDispatcher. immediate`: executes jobs immediately on the main (UI) thread.
Does that mean I can launch a job with it and it will be executed before anything else in the main thread as long as it doesn't suspend/yield? I'm in a situation where I have something like
Copy code
var working = true

fun exec() {
  mySingleThreadedScopeWithImmediate.launch {
    if (working) return

    try {
      working = true
      // do stuff
    } finally {
      working = false
    }
  }
}
because I want this job to be executed as long as it's not already ongoing, and I don't want to put jobs in a queue/wait for a mutex etc. My current implementation uses an
AtomicBoolean
instead of a regular boolean because I wasn't clear on this.
z
• If
exec
is called from the main thread only, then yes, the coroutine will run until its first suspension point immediately. • If
exec
is called from a background thread, then it will be posted to the main thread like the normal main dispatcher. In either case, you wouldn't need an atomic since you're only reading and writing
working
on the main thread.
although i'm curious why your scope is named both "single threaded" and "immediate" – the main thread is single-threaded by definition.
m
Got it, thanks. And well, that's a name I chose for the example because I wanted to avoid using the one from Android, which is
viewModelScope
.
d
An important point: if you are creating nested coroutines using Dispatchers.Main.immediate, only the outermost one is guaranteed to execute immediately when it's launched from the main thread.