https://kotlinlang.org logo
Title
s

Sam

02/15/2019, 10:00 PM
Is it possible to set multiple CompletionHandler on a job?
z

zak.taccardi

02/15/2019, 10:12 PM
IIRC correctly, use. for these kinds of questions, it’s useful to write a quick unit test to confirm
just register multiple completion handlers that output some logs on a scope, and run it
s

Sam

02/15/2019, 10:13 PM
Oh yeah, i did try, i don't see API support
public fun invokeOnCompletion(handler: CompletionHandler): DisposableHandle
seems like the next request overwrites the previous one
b

bdawg.io

02/15/2019, 10:19 PM
@Sam “seems” as in you’re registering two handlers in code and the first one isn’t getting called when you execute the code?
s

Sam

02/15/2019, 10:20 PM
yeah
in my case, i'm using a helper method from a library
library is setting a CompletionHandler for its own cleanup
so i'm wondering how i can set one? I guess, i will have to ask the API to provide another callback
kind of chained implementation
b

bdawg.io

02/15/2019, 10:26 PM
I’m not sure what your test code is, but I wrote one real quick:
suspend fun main() = coroutineScope<Unit> {
    val job = launch { delay(1000) }

    job.invokeOnCompletion { println("handler one called") }
    job.invokeOnCompletion { println("handler two called") }
    job.invokeOnCompletion { println("handler three called") }
}
prints out
handler one called
handler two called
handler three called
s

Sam

02/15/2019, 10:30 PM
Thanks, this does work
I'm not sure why my callback fails
b

bdawg.io

02/15/2019, 10:31 PM
If your callback throws an exception:
Installed [handler] should not throw any exceptions. If it does, they will get caught, wrapped into [CompletionHandlerException], and rethrown, potentially causing crash of unrelated code.
s

Sam

02/15/2019, 10:32 PM
Hmmm, okay, will check the library implementation
Thanks for the tip