Odd question: If i have an outer `suspendCoroutin...
# coroutines
h
Odd question: If i have an outer
suspendCoroutine
and an inner
suspendCoroutine
created inside the first, can I do an "early return" to the outer coroutine without ever resuming the inner one without leaking resources? Ex.
Copy code
suspend fun get(): Int = suspendCoroutine { cont1 ->
   val maybe = LazySuspending { getSomethingOrNull() ?: suspendCoroutine { cont1.resume(0) } }
   
   val result = somethingThatRequiresNonNull(maybe)

   cont1.resume(result)
}
Here I need this because I need to create a "lazy" getter for something that may be null, but the caller expects it to exist. Is this a viable way to solve the problem?
y
It would leak resources AFAIK. Instead, use
suspendCancellableCoroutine
and cancel the inner coroutine when that happens, or just use Arrow's
Raise
instead (which is specifically made for "early-returning"/non-local control flow, and works extremely well with coroutines by using the same cancellation mechanism)
👍 1
z
I'm sure you only posted a simplified version of your real code, but i'd call that out as smelly and trying to fight the framework. I'd try to narrow the scope of what actually happens inside the
suspendCoroutine
and use higher-level coroutine primitives for more things, which make it harder to break structured concurrency.
✔️ 1