Long-running tasks in parallel with Kotlin Flow

Long-running tasks in parallel with Kotlin Flow

I am Amit Shekhar, a mentor helping developers in getting high-paying tech jobs.

In this blog, we will learn about how to run long tasks in parallel with Kotlin Flow in Android.

This article was originally published at amitshekhar.me.

I will be using the following project for the implementation part. The project follows a basic MVVM Architecture for simplicity. You can find the complete code for the implementation mentioned in this blog in the project itself.

GitHub Project: Learn Kotlin Flow

For running the long tasks in parallel, we will be needing the zip operator of Kotlin Flow. So, we need to understand what is a zip operator of Kotlin Flow.

What is a zip operator of Kotlin Flow?

Zip Operator is an operator that combines the emissions of two flow collections together via a specified function and emits single items for each combination based on the results of this function.

zip operator kotlin flow marble diagram

Let's understand the marble diagram with the example code:

val flowOne = flowOf(1, 2, 3)
val flowTwo = flowOf("A", "B", "C")

flowOne.zip(flowTwo) { intValue, stringValue ->
    "$intValue$stringValue"
}.collect {
    println(it)
}

The output will be the following:

1A
2B
3C

Long-running tasks in parallel

A real use case in Android: When we want to run two tasks in parallel and want the results of both tasks in a single callback when both tasks are completed.

Let's see the code implementation.

Suppose we have two long-running tasks.

Long Running Task One:

private fun doLongRunningTaskOne(): Flow<String> {
    return flow {
        // your code for doing a long running task
        // Added delay to simulate
        delay(5000)
        emit("One")
    }
}

Long Running Task Two:

private fun doLongRunningTaskTwo(): Flow<String> {
    return flow {
        // your code for doing a long running task
        // Added delay to simulate
        delay(5000)
        emit("Two")
    }
}

Now, using the zip operator:

fun startLongRunningTask() {
    viewModelScope.launch {
        doLongRunningTaskOne()
            .zip(doLongRunningTaskTwo()) { resultOne, resultTwo ->
                return@zip resultOne + resultTwo
            }
            .flowOn(Dispatchers.Default)
            .catch { e ->
                // handle exception
            }
            .collect {
                // result
            }
    }
}

The output will be the following:

OneTwo

Here, as we have used a zip operator, it runs both tasks in parallel and gives the results of both tasks in a single callback when both tasks are completed.

By zipping two flow collections using the Zip operator, both tasks run in parallel. And we get the result when both get completed. In this way, we get the results of both the flow collections at a time.

Advantages of Zip Operator of Kotlin Flow:

  • Run tasks in parallel.
  • Return the results of tasks in a single callback when all the tasks are completed.

This way we can use the Zip Operator of Flow in Kotlin for running the tasks in parallel.

Master Kotlin Coroutines from here: Mastering Kotlin Coroutines

That's it for now.

Thanks

Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.