kotlinkotlin-coroutinescompletable-futurelong-polling

Long polling with kotlin coroutines


I found this repository at GitHub Long Polling Redis

So in spring boot, we can use a deferred request to hold the client request for several seconds (AppMsgController.java#L72)

and it will send back to the client until the deferred request is filled with the result (AppMsgHandler.java#L74) or until it reaches the timeout.

I also notice this mechanism also can be implemented with CompetableFuture in java using completeOnTimeout.

But I wonder can we use something similar in Kotlin Coroutines?


Solution

  • In Kotlin coroutines there is the Deferred type, which is similar to CompletableFuture in the sense that it represents a value that is not yet available but probably will be in the future (if no error occurs/exception is thrown). @Joffrey pointed out that there is also a CompletableDeferred, which is even closer to ComplatableFuture enabling the user to manually call complete or exceptionallyComplete.

    Deferreds can easily be created with the async extension function on CoroutineScope. If you want to set a timeout, Kotlin has you covered with the withTimeout function that cancels the block of code after a given time.

    Note that withTimeout should be inside async and not the other way around.

    Take a look at this example: https://pl.kotl.in/uYe12ds7g