Manuel Pérez Alcolea
03/04/2025, 2:09 AMMainCoroutineDispatcher.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
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.Zach Klippenstein (he/him) [MOD]
03/04/2025, 2:15 AMexec
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.Zach Klippenstein (he/him) [MOD]
03/04/2025, 2:16 AMManuel Pérez Alcolea
03/04/2025, 2:20 AMviewModelScope
.Dmitry Khalanskiy [JB]
03/04/2025, 9:01 AM