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

taer

05/19/2020, 4:32 PM
Is there a better way to only send a "completion message" on a successful completion of flow when using a cancel? in this case, batchMeetings is my own impl of
flow.chunked()
Copy code
var caughtException = false
        val batches = batchResults(inputFlow, chunkSizePerMessage)
            .map { createResults(it) }
            .catch {
                caughtException=true
                emit(Results.TerminateWithError(it))
            }
        emitAll(batches)
        if(!caughtException) {
            emit(Results.SuccessfulFinish())
        }
Ideally, the Successful finish would only be sent on no exceptions from the upstream flow. That
var caughtException
seems ugly. Is there a cleaner way?
e

elizarov

05/19/2020, 4:47 PM
What's the use-case for that?
Why would you need to emit a message on cancel? What code is going to process that message and how if it is being cancelled?
t

taer

05/19/2020, 4:58 PM
The flow emits a sealed class of (data, error, Success(completedAt). So a normal flow would be D1, D2, D3, D4, Complete(timeStamp) and error case D1, D2, D3, Error
Would it be cleaner for the terminal collector to have the catch and eliminate the Error type all together maybe?
e

elizarov

05/19/2020, 5:00 PM
error's no problem. But why do you need to handle cancellation?
If you just need to handle error just do this:
Copy code
flow
    .onCompletion { emit(Results.SuccessfulFinish()) }
    .catch { emit(Results.TerminateWithError(it) }
That's it
t

taer

05/19/2020, 5:03 PM
Wait.. that's it? I had them in the opposite order.. the catch in front on the onCompletion
and I was getting both
no.. It's still sad. It's actually emitting D1, D2, Success, Fail
letting the error go though w/out mapping to a result class actually worked pretty well. Just mainly curious if there is an onCompletion that wouldn't fire on error case
oh.. that onCompletion is given the exception if it happened.
😉 Thanks!
e

elizarov

05/19/2020, 5:45 PM
Yes. You can do
.onCompletion { if (it != null) emit(...) }
.
We were actually thinking on having a separate operator just for "successful completion" but have not figured out a good name for it that people would not be confusing with
onCompletion
t

taer

05/19/2020, 10:22 PM
only input would be onError() and onSuccess(). That's not obvious though still
5 Views