Hey, might be a dumb question but I can’t seem to ...
# android
a
Hey, might be a dumb question but I can’t seem to figure out what to use, I have a function making a network call that will return an element that you can wait on to retrieve the response and that can be consumed by multiple listeners. For now I have a Flow but this seems overkill for a single return value.
The Swift equivalent would be something like a Publisher I guess
m
Just a
Deferred
maybe? You could just
await
it multiple times.
You want to do the network call only once, right?
a
Yes, I want to do the call only once but be able to retrieve the value multiple times, a Flow works since I can emit and then collect multiple times
f
did you try
BehaviourSubject
from rxjava?
m
@Antoine Gagnon But a
Flow
is cold, which means that you will trigger the network call again every time you collect it. So a
Deferred
seems like a better fit to me.
Something like this:
Copy code
suspend fun performNetworkCall() = network.call()

suspend fun service() = coroutineScope {
    val value = async { performNetworkCall() }

    listener1(value)
    listener2(value)
}

suspend fun listener1(value: Deferred<Data>) {
    println("Listener 1: ${value.await()}")
}

suspend fun listener2(value: Deferred<Data>) {
    println("Listener 2: ${value.await()}")
}
a
That seems like a great solution! I didn’t catch the issue with the Flow, I’m pretty new to them, thanks!