Kotlin Flow Zip Operator for Parallel Multiple Network Calls

Authors
  • Amit Shekhar
    Name
    Amit Shekhar
    Published on
Kotlin Flow Zip Operator for Parallel Multiple Network Calls

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

In this blog, we will learn about the Kotlin Flow Zip Operator and how to make multiple network calls in parallel using it.

Let's get started.

First, let's understand what is a zip operator in Kotlin Flow.

What is a zip operator in 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

Parallel Multiple Network Calls

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

I will be using this project for the implementation part. You can find the complete code for the implementation mentioned in this blog in the project itself.

We will take the example of ParallelNetworkCallsViewModel which is present in the project.

Basically, this ParallelNetworkCallsViewModel is a ViewModel that is associated with ParallelNetworkCallsActivity which triggers the ViewModel to fetch the list of users to render into the UI. The ParallelNetworkCallsViewModel, then asks the data layer for the list of users using the ApiHelper. The ViewModel makes the two network calls in parallel which are as getUsers and getMoreUsers.

So, here we have two flow of network calls:

  • getUsers
  • getMoreUsers

As you can see below, the ViewModel uses the Kotlin Coroutines and LiveData. Also, notice that the zip operator is used in the below code.

class ParallelNetworkCallsViewModel(
    private val apiHelper: ApiHelper,
    private val dbHelper: DatabaseHelper
) : ViewModel() {

    private val users = MutableLiveData<Resource<List<ApiUser>>>()

    init {
        fetchUsers()
    }

    private fun fetchUsers() {
        viewModelScope.launch {
            users.postValue(Resource.loading(null))
            apiHelper.getUsers()
                .zip(apiHelper.getMoreUsers()) { usersFromApi, moreUsersFromApi ->
                    val allUsersFromApi = mutableListOf<ApiUser>()
                    allUsersFromApi.addAll(usersFromApi)
                    allUsersFromApi.addAll(moreUsersFromApi)
                    return@zip allUsersFromApi
                }
                .flowOn(Dispatchers.IO)
                .catch { e ->
                    users.postValue(Resource.error(e.toString(), null))
                }
                .collect {
                    users.postValue(Resource.success(it))
                }
        }
    }

    fun getUsers(): LiveData<Resource<List<ApiUser>>> {
        return users
    }

}

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

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

Advantages of Zip Operator of Flow

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

This way we can use the Zip Operator of Flow to solve the interesting problem.

Show your love by sharing this blog with your fellow developers.

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.