Tash
05/27/2020, 2:56 AMcallbackFlow is it necessary to call close(exception) if an operation inside it throws? i.e.
callbackFlow {
try {
val result = somethingThatThrows() // Try-catch or just let it be?
offer(result)
} catch (exception) {
close(exception)
}
awaitClose { ... }
}Dominaezzz
05/27/2020, 3:13 AMcallbackFlow .
If the exception means that offer /`send` will stop being called, then yes, you must call close.Tash
05/27/2020, 3:55 AMfun processedEvents(coordinator: EventCoordinator): Flow<Event> {
return callbackFlow {
val eventListener = object: EventListener {
override fun onEvent(event: Event) {
// Can throw
val processedEvent = coordinator.processEvent(event)
offer(processedEvent)
}
}
coordinator.addEventListener(eventListener)
awaitClose { coordinator.removeEventListener(eventListener) }
}
}Tash
05/27/2020, 4:03 AMprocessEvent(...) throws in that example, the listener should be removed, i.e. awaitClose block must run
So, sounds like needs to be surrounded with try/catch + close 🤔Dominaezzz
05/27/2020, 4:09 AMoffer.
val r = runCatching { coordinator.processEvent(event) }
r.fold({ offer(it) }, { close(it) })Dominaezzz
05/27/2020, 4:10 AMfun processedEvents(coordinator: EventCoordinator): Flow<Event> {
return callbackFlow {
val eventListener = object: EventListener {
override fun onEvent(event: Event) {
offer(event)
}
}
coordinator.addEventListener(eventListener)
awaitClose { coordinator.removeEventListener(eventListener) }
}.map { coordinator.processEvent(it) }
}Dominaezzz
05/27/2020, 4:11 AMcoordinator.processEvent is.Tash
05/27/2020, 4:23 AMmap is kinda nice. yeah, coordinator.processEvent internally calls a getter and maps the incoming argument to some new value. it does not inflict any side-effects.Tash
05/27/2020, 4:25 AMawaitClose is triggered only when `close`/`cancel` have been explicitly called. i.e., letting the processEvent exception propagate would not have caused awaitClose to be calledDominaezzz
05/27/2020, 4:49 AMmap) cancels/finishes collection (i,e throws exception)Tash
05/27/2020, 5:18 AMmap or try/catch , awaitClose would not get called if processEvent threwTash
05/27/2020, 5:18 AM