https://kotlinlang.org logo
#arrow
Title
# arrow
d

dave08

02/20/2023, 3:46 PM
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

simon.vergauwen

02/20/2023, 3:51 PM
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")
6 Views