Kotlin Coroutines in Android — Part 9

Combining multiple tasks with the operators on collections

Andrea Bresolin
Kin + Carta Created
2 min readApr 5, 2019

--

As you probably know, Kotlin provides out of the box a good set of operators on collections. If you’re familiar with RxJava, those operators will remind you of it. There are cases when it’s convenient to process the items in a collection as if it was a stream, like we were used to with RxJava. We can achieve the same kind of processing by combining coroutines and the Kotlin operators on collections.

Here is an example:

In this code, we have a collection. For each value in the collection, we fetch some data from a repository by passing the value as a parameter. Each fetching happens in parallel with the others because we use ioTaskAsync from our DSL, then we collect all the results in the next step by calling await() on each Deferred returned by ioTaskAsync. In the following step, we fetch the data sequentially by calling ioTask and we return the sum of all the results.

This was just a simple example, but it should give you an idea of the whole process. We can use coroutines and still have a fluent API to process the data as if it was part of a stream.

What’s next

This part was short because its purpose was just to show an alternative approach in combining multiple coroutines. In the next part of this series, we’ll see how we can transform some code that has callbacks into a coroutine-friendly version.

Get the source code

The source code for this series can be found on GitHub. It’s an example Android project that covers multiple cases. Download it and play with it.

Missed the other parts of this series?

If you’ve missed the other parts of the Kotlin Coroutines in Android series, take a look at the introduction and check the full list of topics.

--

--