Hi, is there a way to globally attach some code lo...
# coroutines
g
Hi, is there a way to globally attach some code logic to coroutine lifecycle methods?
l
try finally?
z
Globally, no, but you could provide a context with a special ContinuationInterceptor that implements something like this.
g
I would like to track the start and the completion of a coroutine. Is ContinuationInterceptor viable for this? Thanks for the suggestion
l
Here's a basic example of what I was talking about:
Copy code
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
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
You could look at what the coroutine debug agent does, sounds similar to that.
­čĹŹ 1