https://kotlinlang.org logo
Title
g

Grantas33

11/01/2020, 4:08 PM
Hi, is there a way to globally attach some code logic to coroutine lifecycle methods?
l

louiscad

11/01/2020, 4:27 PM
try finally?
z

Zach Klippenstein (he/him) [MOD]

11/01/2020, 6:41 PM
Globally, no, but you could provide a context with a special ContinuationInterceptor that implements something like this.
g

Grantas33

11/01/2020, 11:08 PM
I would like to track the start and the completion of a coroutine. Is ContinuationInterceptor viable for this? Thanks for the suggestion
l

louiscad

11/02/2020, 2:04 AM
Here's a basic example of what I was talking about:
inline fun trackFunction(block: () -> Unit) {
    try {
        println("entered")
        block()
    } finally {
        println("exited")
    }
}

suspend fun whatever() {
    trackFunction {
        doStuff()
        val result = doOtherStuff()
        if (result.isNotWhatIWant) {
            return
        }
    }
}
That doesn't require you to play with the internals of coroutines
You just have to wrap the call/coroutine with whatever you want.
g

Grantas33

11/02/2020, 9:05 PM
thanks for the suggestion, though I am searching for some global solution where I could hook some code to the lifecycle events of every kotlin coroutine in the java process. I want to build something like a profiler to monitor coroutines. ContinuationInterceptor so far seems too limited for my use case. Thinking of looking into AOP solutions such as ByteBuddy
z

Zach Klippenstein (he/him) [MOD]

11/02/2020, 9:53 PM
You could look at what the coroutine debug agent does, sounds similar to that.
👍 1