Coroutine Basics: Converting callbacks to coroutines

Vineeth Venudasan
2 min readFeb 11, 2020

It is fairly easy to convert callback based code into Kotlin coroutine based code, bringing with it advantages of having asynchronous code that looks very much like synchronous code, promising easier readability.

Here is some code where we make a call to an API using the OkHttp library, with a callback to handle the response:

To test if this method works, we write a test method that look like the snippet below. Considering that there is a callback, I have had to use the awaitly library.

Yuck!

Coroutines can make this look better, I promise. Let’s get started.

For this, we would require a suspendCoroutine builder. This is the modified code

Doesn’t look all that different, does it? But have a look at the test method now:

You could wrap your OkHttpClient client like how it was done above, or you could even write an Extension function. All the usage of the OkHttpClient after that would look like how it is in the test case above.

Notice how asynchronous code now looks like synchronous code?

No need for an external awaitly library (for testing), no more callbacks in the calling code, I see this as a win.

This kind of succinct code is what Kotlin had promised us.

Conclusion

If you have asynchronous frameworks in your Kotlin projects, and if they rely on callbacks, a consider creating a wrapper around it so that you can use coroutines instead of callbacks for cleaner and easier maintainable code.

The next developer working on your code-base will thank you.

Further Information

Callbacks and Kotlin Flows: https://medium.com/@elizarov/callbacks-and-kotlin-flows-2b53aa2525cf

Introduction to Coroutines by Roman Elizarov: https://www.youtube.com/watch?v=_hfBv0a09Jc

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Written by Vineeth Venudasan

Backend Engineer / Software Consultant. The views expressed here are my own and does not necessarily represent my employer’s positions, strategies or opinions

No responses yet

Write a response