https://kotlinlang.org logo
#android
Title
# android
a

Antoine Gagnon

03/02/2020, 7:44 PM
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

marstran

03/02/2020, 7:58 PM
Just a
Deferred
maybe? You could just
await
it multiple times.
You want to do the network call only once, right?
a

Antoine Gagnon

03/02/2020, 8:20 PM
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

Faraz

03/03/2020, 10:15 AM
did you try
BehaviourSubject
from rxjava?
m

marstran

03/03/2020, 10:32 AM
@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

Antoine Gagnon

03/03/2020, 2:39 PM
That seems like a great solution! I didn’t catch the issue with the Flow, I’m pretty new to them, thanks!
4 Views