Testing Coroutines and Asynchronous Calls
Explore how to write and test asynchronous Kotlin functions using coroutines. Understand marking functions with suspend, using Dispatchers.IO for thread context, and mocking withContext and async to create efficient non-blocking code. This lesson helps you ensure your asynchronous calls are reliable and well-tested without actual delays.
We'll cover the following...
The getAirportStatus() function is making synchronous calls, one at a time, to the getAirportData() function. If we receive a large number of airport codes, then making blocking calls, one by one, won’t be efficient. If we make the calls to getAirportData() asynchronous, using coroutines, then we can get a better throughput. Of course, we’ll have to test first and then write the code for asynchronous execution.
Making asynchronous calls
For getAirportStatus() to make asynchronous calls, we have to do three things. First, mark the function with the suspend keyword. Then execute the body of the function in the context of a Dispatchers.IO thread pool. Finally, embed the calls to getAirportData() within async calls and await for the results by applying the techniques we saw in the previous chapter (Asynchronous Programming). We’ll ...