I am trying to find an equivalent pattern for `by ...
# coroutines
s
I am trying to find an equivalent pattern for
by lazy
variable with coroutines. I can call
async(start = Lazy){ expensiveCalculation }
but afaik it does not make the computation optional, only delayed. What am I missing?
r
You could define your variable as a Flow, and consume it whenever you want the lazy access to happen
Copy code
val myFlow = flow {
   emit(WHATEVER)
}
...
val getMyStuffLazily = myflow.collect()
At first glance, it wouldn’t solve the issue for multiple access to the variable, but it may be at least an interesting way to start thinking about modeling the issue
l
@spand You might be looking for a suspending lazy (full discolure, I authored it): https://github.com/LouisCAD/Splitties/tree/main/modules/coroutines#suspending-version-of-lazy
👍 1
👀 1
s
Nice. Thanks for the pointer @louiscad Seems simple enough
🙂 1
g
but afaik it does not make the computation optional, only delayed
What do you mean? computation is optional, until someone call .await() on it
it should work exactly the same as Louis’ helper function
l
If wrapped in a
lazy
. Otherwise, it can keep a
CoroutineScope
alive (which doesn't matter in most cases though).
g
but why it should be wrapped to lazy? if async already lazy
r
async is not lazy
g
it is!
if you passed start param with lazy
how it showed above in Johannes example
r
ah, true
l
We're talking about 2 things. Let me explain
but why it should be wrapped to lazy?
To not put a (lazy) child coroutine in the host
CoroutineScope
that could keep it alive if
await()
is never called and the scope never cancelled.
g
if await is never called, coroutine is not started if it start = Lazy
ahhh
s
But the scope will not return unless all children have completed (which then means never according to my small tests)
g
I got what you meant
l
@gildor Yes, it's never started, but the scope still has an uncompleted child coroutine
g
yes, this coroutine is not active, but it keeps scope active, it’s true
yeah, got what you meant
usually it’s not an issue, but can be a pretty bad gotcha in some cases
l
Exactly
Yeah a bad gotcha rather than a good one 😅
r
I really dug your implementation Louis, TIL something new 😄 Thanks for sharing!
g
actually i’m not sure that it’s expected behaviour in this case, probably would be better to not mark state as active until coroutine is started, maybe I don’t see some cases when current behaviour is needed
l
@renatomrcosta Happy it's helpful :)
@gildor I think it could cause problems to let the scope die when it has not yet started coroutines because you can start a coroutine later from non suspending code, and if it fails because the
coroutineScope
"was tired waiting", that'd be another bad gotcha