Quick question, and hopefully a quick answer :slig...
# coroutines
s
Quick question, and hopefully a quick answer 🙂 : How does one terminate a
Flow<T>
(successfully or with an error)? The
FlowCollector<T>
only has an
emit
method.
d
From which end do you want to terminate from? Sender or receiver?
s
The sender/producer side.
p
Throw a CancellationException for cancelling it or throw an exception if you want to throw an exception
d
It depends on how you are creating the flow. Are you using the
flow { }
builder?
j
for successful completion just let the block end
s
Yep… it seems exiting the
flow { ... }
lambda, it ends…
Ah… Thanks!
j
for error, throw any exception you like
s
How would I use a
FlowCollector
in a callback that repeatedly calls back?
j
you probably want flowViaChannel
you can close the channel to complete
s
Thank you!
Without using Channels, would something like this work?
Copy code
val gpsCoordsFlow: Flow<Pair<Double, Double>> = flow {
        coroutineScope {
            gpsManager.registerListener { coord ->
                launch { emit(coord) }
        }
        suspendCoroutine<Nothing> { /* nothing */ }
    }
(would need extra code to properly un-register the listener, etc.)
j
the downside of that is it launches one coroutine per callback invocation whereas a channel only creates one coroutine in total
s
Or share the Flow to avoid multiple registrations: 🙂 https://github.com/Kotlin/kotlinx.coroutines/issues/1086