If I need a `coroutineScope { }` in a suspend func...
# arrow
d
If I need a
coroutineScope { }
in a suspend function, do I need to put the
either { }
outside or inside of it (does it matter)? Or maybe there's a variant of
either { }
that does that?
s
They behave slightly different, and you should use whatever makes sense for your use-case. If
either
is inside
coroutineScope
then it can never cancel the
coroutineScope
.
Copy code
coroutineScope {
  either<String, Int> {
    launch { delay(1_000_000) }
    ensureNotNull(null) { "Fails" }
  } // Either.Left("Fails")
} // waits 1_000_000 completion
If you
either
is outside of
coroutineScope
it can cancel or short-circuit the
coroutineScope
.
Copy code
either<String, Int> {
  coroutineScope {
    launch { delay(1_000_000) }
    ensureNotNull(null) { "Fails" }
  } // Finishes "immediately", and cancels delay
} // Either.Left("Fails")