Search code examples
androidkotlinkotlin-coroutinescontinuations

Any way to "join" a currently-active Continuation in Kotlin Coroutines?


I feel like I'm close here.

Let's say I have a method with a suspendCancellableCoroutine: (Sorry for any syntactical/etc. errors, just trying to get an idea down)

suspend fun foo(): String {
    suspendCancellableCoroutine {
       val listener = object : Listener {
           override fun theThingHappened() {
               it.resume("The result")
           }
       }

       // Long involved process
       thirdPartyThing.doSomethingWithListener(listener)
    }
}

I call that method once, it does its thing and returns a string. But if another process calls the same method while the first CancellableContinuation is still running, is there a way to just join it and return the same result?

The reason I'm asking is that buried in my suspendCancellableCoroutine, there's a third-party method that can only run once at any given time, and attempting to run it again before the first one has completed will throw an error.

So let's say that foo() takes 10 seconds to run. It gets called once and will return the result string. But suppose that 5 seconds later another process calls it. Instead of spawning off another suspendCancellableCoroutine, can I just have the 2nd call wait for the first to finish and return that value as well?

I hope I've described this well.


Solution

  • Mr. Sean McQuillan wrote an excellent article on Medium, titled Coroutines On Android (part III): real work specifically addressing this problem, where he explored various solutions. One of the approaches he discusses is the use of coroutines. For example, you can manage repetitive requests using one of the methods he suggested:

    1. Cancel the previous work
    2. Queue the next work
    3. Join previous work

    I highly recommend reading his article on Medium.