https://kotlinlang.org logo
#coroutines
Title
# coroutines
l

Luis Munoz

12/11/2019, 9:44 PM
I want to suspend from calling a function until some variable is set, what is the best way to do that? It is sort of the reverse of how I normally think of a Mutex. Is the best way just to create a mutex that is locked and just try to lock it again, and when my variable is set just unlock it, which will then allow calling the function
l

louiscad

12/11/2019, 9:49 PM
Are you looking for a kind of suspending
Lazy
?
a

Anders Mikkelsen

12/11/2019, 9:50 PM
You could access it through a suspended function that simply returns the field on every subsequent call
l

Luis Munoz

12/11/2019, 9:54 PM
@louiscad not sure what suspending lazy means
I have a method that sends a message but I should only send messages after some event happened. So for any call on the method that sends the messages i want to suspend until the event happened.
y

yousefa2

12/11/2019, 9:58 PM
Maybe you can use Flow to start with generating the value for this variable then map to run your function
j

Jason Ostrander

12/11/2019, 10:59 PM
If you're just waiting for a value to be set, you could use a CompletableDeferred
1
b

bohsen

12/12/2019, 7:22 AM
You could also use an
actor
, but as @yousefa2 mentioned you should probably use
flow
. This actually sounds like an operator of some kind on
Flow
. But it also depends on if you control the mechanism that emits the
Event
. Can it return a
Flow
?
l

louiscad

12/12/2019, 9:55 PM
@Luis Munoz You have
by lazy { someInitializingCode() }
, that only works for blocking code (not suspending code).
5 Views