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

streetsofboston

05/06/2019, 2:58 PM
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

Dominaezzz

05/06/2019, 3:07 PM
From which end do you want to terminate from? Sender or receiver?
s

streetsofboston

05/06/2019, 3:09 PM
The sender/producer side.
p

Paul Woitaschek

05/06/2019, 3:11 PM
Throw a CancellationException for cancelling it or throw an exception if you want to throw an exception
d

Dominaezzz

05/06/2019, 3:11 PM
It depends on how you are creating the flow. Are you using the
flow { }
builder?
j

jw

05/06/2019, 3:12 PM
for successful completion just let the block end
s

streetsofboston

05/06/2019, 3:12 PM
Yep… it seems exiting the
flow { ... }
lambda, it ends…
Ah… Thanks!
j

jw

05/06/2019, 3:12 PM
for error, throw any exception you like
s

streetsofboston

05/06/2019, 3:13 PM
How would I use a
FlowCollector
in a callback that repeatedly calls back?
j

jw

05/06/2019, 3:14 PM
you probably want flowViaChannel
you can close the channel to complete
s

streetsofboston

05/06/2019, 3:17 PM
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

jw

05/06/2019, 3:26 PM
the downside of that is it launches one coroutine per callback invocation whereas a channel only creates one coroutine in total
s

streetsofboston

05/06/2019, 3:28 PM
Or share the Flow to avoid multiple registrations: 🙂 https://github.com/Kotlin/kotlinx.coroutines/issues/1086
2 Views