Skip to main content

Coroutines and callbacks


Callbacks in Java are probably the most basic way to perform executions/send actions between classes. If you have chosen to use coroutines in a project, you want to keep the same style everywhere. But what if some of the libraries you use, are still using callbacks?

No worries, Kotlin coroutines are easily integrated with callbacks. It's just a small workaround to make.

Let's think of a very simple use case:
interface MyAwesomeInterface<T> {
    fun executeAsync(callback: (T?, Throwable?) -> Unit)
}

In this case, what can be done, is to wrap it in a suspendCoroutine. So, le'ts build an extension function for it:
suspend fun <T> MyAwesomeInterface<T>.execute(): T =
    suspendCoroutine { continuation -> //notice the continuation that you get
        executeAsync { value, exception ->
            if(exception != null)
                continuation.resumeWithException(exception)
            else
                continuation.resume(value as T)
        }
    }

The continuation that you get from the suspendCoroutine is nothing else than just a representation of the value returned by your own interface implementation.

But what if our MyAwesomeInterface has a cancel operation? Consider the example below:
interface MyAwesomeInterface<T> {
    fun executeAsync(callback: (T?, Throwable?) -> Unit)
    fun cancel()
}

In this case, what comes in handy is the suspendCancellableCoroutine. It is nearly the same as the suspendCoroutine but it offers a new aditional operation:
suspend fun <T> MyAwesomeInterface<T>.execute(): T =
    suspendCancellableCoroutine { continuation ->
        executeAsync { value, exception ->
            if(exception != null)
                continuation.resumeWithException(exception)
            else
                continuation.resume(value as T)
        }
       continuation.invokeOnCancellation { cancel() }
    }

Note: These implementations are single-shot operation.

But what if you would have to observe an asynchronous stream of values through callbacks? This can be achieved with the help of the Flow API. If you still haven't check it up, the docs are pretty nice, or you can just go quickly though this article (even though it's mostly for Android developers).

In this case, the callbackFlow comes to save the day:

 fun <T : Any> MyAwesomeInterface<T>.execute(): Flow<T> =
   callbackFlow {
       executeAsync { value, exception ->
            when {
                exception != null -> close(exception)
                value == null -> close()
                else-> offer(value as T)
            }
        }
        awaitClose{ cancel() }
    }

There are some important things to note here:
 - Our execute() extension function is no longer a suspend function
 - The close() is used to notify for a failure/success
 - The offer() is called each time a new data has arrived.

Important note: Not calling the awaitClose() would take you directly to ClosedSendChannelException if the method is executed n+1 times.

But my interface doesn't have a cancel() method.

Than just unregister the listener. The cancel() method is there also to represent  the context of removing it.

A few notes about backpressure.

In cases when the operation happens too fast and the coroutine cannot handle it, the best thing is to replace the offer() method with sendBlocking().

In the opposite case, when the values should not arrive too fast, just put a .buffer(Channel.UNLIMITED) after the callbackFlow:
 fun <T : Any> MyAwesomeInterface<T>.execute(): Flow<T> =
   callbackFlow {
       executeAsync { /* same thing here */}
        awaitClose{ cancel() }
    }.buffer(Channel.UNLIMITED)

Don't forget that this case, comes with a memory cost.

Conclusion:

Actually, these feature of callbacks are awesome and pretty safe in my opinion. They open a wide area of possibilities to improve your libraries, create a new one, or even shorten some parts of code from your current project.

Stavro Xhardha

Popular posts from this blog

Modularizing your Android app, breaking the monolith (Part 1)

Inspired by a Martin Fowlers post about Micro Frontends, I decided to break my monolithic app into a modular app. I tried to read a little more about breaking monolithic apps in Android, and as far as I got, I felt confident to share my experience with you. This will be some series of blog posts where we actually try to break a simple app into a modularized Android app.

Note: You should know that I am no expert in this, so if there are false statements or mistakes please feel free to criticize, for the sake of a better development. 

What do you benefit from this approach:
Well, people are moving pretty fast nowadays and delivery is required faster and faster. So, in order to achieve this, modularising Android apps is really necessary.You can share features across different apps. Independent teams and less problems per each.Conditional features update.Quicker debugging and fixing.A feature delay doesn't delay the whole app. As per writing tests, there is not too much difference about…

What I learned from Kotlin Flow API

I used to check the docs and just read a lot about flows but didn't implement anything until yesterday. However, the API tasted really cool (even though some operations are still in Experimental state).Prerequisites: If you don't know RxJava it's fine. But a RxJava recognizer would read this faster.Cold vs Hot streamsWell, I really struggled with this concept because it is a little bit tricky. The main difference between cold and hot happened to be pretty simple: Hot streams produce when you don't care while in cold streams, if you don't collect() (or RxJava-s equivalent subscribe()) the stream won't be activated at all. So, Flows are what we call cold streams. Removing the subscriber will not produce data at all, making the Flows one of the most sophisticated asynchronous stream API ever (in the JVM world). I tried to make a illustration of hot and cold streams: Since I mentioned the word asynchronous this implies that they do support coroutines also. Flows vs…

From Gson to Moshi, what I learned

There is no doubt that people are getting away from GSON and I agree with those reasons too. The only advantage GSON has over other parsing libraries is that it takes a really short amount of time to set up. Furthermore, the most important thing is that Moshi is embracing Kotlin support.

First let's implement the dependency:
implementation("com.squareup.moshi:moshi:1.8.0") It's not a struggle to migrate to Moshi. It's really Gson look-a-like. The only thing to do is annotate the object with @field:Json instead of @SerializedName (which is Gsons way for JS representation):

data class User( //GSON way @SerializedName("name") val name: String, @SerializedName("user_name") val userName: String, @SerializedName("last_name") val lastName: String, @SerializedName("email") val email: String ) data class User( //Moshi way @field:Json(name = "name") val name: String, @field:Json(name = "user_name…