Skip to content
Go back

Parallel Network Calls and Error Handling in Kotlin Flow — zip, catch, and emitAll

Parallel Network Calls and Error Handling in Kotlin Flow

Two patterns appear in almost every real Android codebase: running two API calls at the same time and handling failures gracefully. The previous post covered sequential calls with flatMapConcat. This post covers parallel calls with zip and two strategies for handling errors — combined and per-task.


zip: Running Two Calls in Parallel

zip takes two Flows and pairs their emissions. Both Flows start collecting at the same time — in parallel.

val footballFlow: Flow<List<User>> = apiHelper.getFootballUsers()
val cricketFlow: Flow<List<User>> = apiHelper.getCricketUsers()

footballFlow
    .zip(cricketFlow) { footballList, cricketList ->
        findSportsLovers(footballList, cricketList)
    }
    .flowOn(Dispatchers.IO)
    .collect { sportsLovers ->
        showInUI(sportsLovers)
    }

Even though cricketFlow is written after footballFlow in the code, both calls launch simultaneously. zip waits until both have emitted and then combines the results in the lambda.

If the football call takes 1 second and the cricket call takes 2 seconds, the combined result arrives after 2 seconds — not 3. That is the value of parallelism: total time = the slower of the two, not the sum.


When zip Is the Right Choice

zip has a firm requirement: both results must be available before the lambda runs. This makes it the right tool when:

If the second call depends on the first call’s result — for example, you need the uploaded image URL before calling updateProfile — then zip is wrong. Use flatMapConcat for that case, since the calls must run in series.


Error Handling: The catch Operator

catch is a Flow operator that intercepts any exception thrown upstream in the pipeline.

apiHelper.getUsers()
    .map { convertToUsers(it) }
    .catch { e ->
        uiState.value = UiState.Error(e.toString())
    }
    .collect { users ->
        uiState.value = UiState.Success(users)
    }

If anything upstream throws — the network call, the map transformation, anything — it lands in catch. The collector is never called with partial or broken data.

catch only intercepts exceptions that originate upstream of it. Exceptions thrown inside .collect { } itself are not caught here.


Combined catch with zip: One Failure Cancels Both

When a combined catch sits at the end of a zip chain:

footballFlow
    .zip(cricketFlow) { a, b -> combine(a, b) }
    .catch { e ->
        uiState.value = UiState.Error(e.toString())
    }
    .collect { result -> showInUI(result) }

If either footballFlow or cricketFlow throws an error, both tasks are cancelled and the error reaches catch. This is the correct behaviour when a partial result has no value — you need both API calls to succeed before showing anything.


Per-Task catch: Independent Error Handling

Sometimes one failure should not stop the other. Suppose one API going down should still let the other call succeed and show partial data. The solution is to add a catch block to each Flow individually, before they are zipped:

val footballFlow = apiHelper.getFootballUsers()
    .catch { emitAll(flowOf(emptyList())) }   // fallback: empty list on failure

val cricketFlow = apiHelper.getCricketUsers()
    .catch { emitAll(flowOf(emptyList())) }   // fallback: empty list on failure

footballFlow
    .zip(cricketFlow) { footballList, cricketList ->
        findSportsLovers(footballList, cricketList)
    }
    .collect { result -> showInUI(result) }

Now if footballFlow fails, it emits an empty list instead of propagating the error. cricketFlow is unaffected and continues normally. The zip lambda receives an empty list from the failed call and the real data from the successful one. The app does not crash, and the user sees whatever partial data is available.


emitAll: The Fallback Mechanism

Inside a catch block, you cannot call emit() directly — catch does not provide an emitter. Instead, use emitAll:

.catch { exception ->
    emitAll(flowOf(emptyList()))    // emit a fallback value downstream
    // or: emitAll(localCacheFlow)  // fall back to local cache
}

emitAll takes any Flow and emits all of its values into the current stream. The downstream collector sees the fallback values as if they had been emitted normally — it has no knowledge that an error occurred upstream.

Common fallback patterns:

// Emit an empty list
.catch { emitAll(flowOf(emptyList())) }

// Fall back to cached data
.catch { emitAll(localDatabase.getUsers()) }

// Emit a default object
.catch { emitAll(flowOf(User.default())) }

Practice Problem from the Class

The class notes include a worked example worth tracing through:

Make two network calls in parallel. After both succeed, save the combined data to a database. Then display the result.

val call1 = apiHelper.getNetworkData1().flowOn(Dispatchers.IO)
val call2 = apiHelper.getNetworkData2().flowOn(Dispatchers.IO)

call1
    .zip(call2) { data1, data2 ->
        data1 + data2          // combine — plain value, use zip transform
    }
    .flatMapConcat { combined ->
        database.save(combined)    // DB call returns Flow — use flatMapConcat
    }
    .catch { e ->
        uiState.value = UiState.Error(e.toString())
    }
    .collect {
        uiState.value = UiState.Success
    }

Step by step:

  1. zip runs both network calls in parallel. Its lambda combines the results into a plain value — no Flow returned, so zip’s own transform is sufficient.
  2. flatMapConcat takes that combined value and passes it to database.save(), which is a Flow-returning operation — so flatMapConcat is required (not map).
  3. A single catch at the end handles any failure across the whole pipeline.

Summary

Operator / PatternPurpose
zipRun two Flows in parallel; wait for both; combine results
Combined catchOne failure cancels all; single error state for the pipeline
Per-task catch + emitAllEach failure handled independently; partial results still flow
emitAllEmit a fallback Flow’s values inside a catch block

The next and final post covers the full debounced search pipeline — debounce, filter, distinctUntilChanged, flatMapLatest — and compares flatMapLatest vs flatMapConcat vs flatMapMerge so you always choose the right one.


Share this post on:

Previous Post
Debounced Search in Android with Kotlin Flow — debounce, filter, distinctUntilChanged, flatMapLatest
Next Post
map vs flatMapConcat in Kotlin Flow — When Your Transformation Returns a Flow