“Flow invariant is violated” is an IllegalStateException from the flow { } builder. It means emit ran in a different coroutine context than the one collecting the flow. The builder checks this on every emit. Two different mistakes trigger it. Each has its own message. Calling emit inside withContext(Dispatchers.IO) gives the “Flow was collected in” message. It names two different contexts. Calling emit inside a launch gives “Emission from another coroutine is detected”. The first fix is to emit from the builder’s own coroutine and move the dispatcher change to flowOn. The second needs channelFlow, because flow doesn’t allow concurrent emits at all. One catch remains in the concurrent version. Two producers can deliver in either order. So a slow cache read can land after the fresh network result and overwrite it. Cancel the cache read once the network result arrives.
A feed repository that crashes the first time it leaves the main thread
The running example is a feed screen. It shows cached posts first, then fresh posts from the network. The first version of the repository read the cache on the main thread. A reviewer asked for the disk read to move to Dispatchers.IO. This is the change that shipped.
class FeedRepository(private val cache: FeedCache, private val api: FeedApi) {
fun observeFeed(): Flow<List<Post>> = flow {
withContext(Dispatchers.IO) {
emit(cache.read())
}
emit(api.fetch())
}
}
The screen collects this in viewModelScope. The first emit throws before any post reaches the UI.
java.lang.IllegalStateException: Flow invariant is violated:
Flow was collected in [BlockingCoroutine{Active}@11cf7de2, BlockingEventLoop@17f67224],
but emission happened in [DispatchedCoroutine{Active}@18f95425, Dispatchers.IO].
Please refer to 'flow' documentation or use 'flowOn' instead
That output comes from our repro, so the collector is runBlocking. In an app, the first bracket names the ViewModel’s coroutine and its main dispatcher. The second bracket names the context that called emit.
Cause one: flow invariant is violated when emit leaves the collector’s context
A cold flow runs its builder inside the collector’s coroutine. The Flow interface docs call this context preservation. A flow keeps its execution context to itself. It never leaks that context to downstream operators. The docs name flowOn as the only way to change a flow’s context. Their sample marks withContext around emit as prohibited.
The rule protects the collector. Code inside collect { } assumes it runs where it was called. In a ViewModel, that’s the main thread. If emit ran on an IO thread, the collector lambda would run there too. A state update meant for the UI would then happen on a worker thread. So the builder checks every emit. It compares the current context with the collector’s context. Any mismatch throws the message above.
The reviewer’s goal was fine. Only the placement was wrong. withContext around the read is allowed, because the read returns a value. The emit then runs back in the collector’s context. Our run of flow { emit(withContext(Dispatchers.IO) { ... }) } did the read on a DefaultDispatcher-worker thread. It collected on main without an error. The bug is withContext around emit.
Cause two: launch inside flow { } emits from another coroutine
The developer who got the crash read the message as a thread problem. They also wanted the cache and the network to load in parallel. So the second version launched both inside the builder.
fun observeFeed(): Flow<List<Post>> = flow {
coroutineScope {
launch { emit(cache.read()) }
launch { emit(api.fetch()) }
}
}
Neither launch changes the dispatcher. It still crashes, with a different message.
java.lang.IllegalStateException: Flow invariant is violated:
Emission from another coroutine is detected.
Child of StandaloneCoroutine{Active}@e50a6f6, expected child of BlockingCoroutine{Active}@11cf7de2.
FlowCollector is not thread-safe and concurrent emissions are prohibited.
To mitigate this restriction please use 'channelFlow' builder instead of 'flow'
This check looks at the Job, not the thread. A launch creates a new coroutine with its own job. Two of them can call emit at the same time. A FlowCollector has no locking, so the builder rejects any emit from a child coroutine. The maintainers chose this in kotlinx.coroutines issue #1210, filed in May 2019. They kept the collector non-thread-safe for speed. They added channelFlow for concurrent producers. Those call send instead of emit.
We ran four versions of the repository with kotlinc 2.4.20 and kotlinx.coroutines 1.11.0 on JDK 25. The fake cache took 300 ms and the fake API took 100 ms. The withContext version and the launch version printed the two messages above. Adding .flowOn(Dispatchers.IO) to the launch version still threw “Emission from another coroutine is detected”. flowOn moves the whole builder to another context. The two launches are still separate coroutines inside it.
The fix depends on whether the two loads must run at the same time
If the cache and the network can run one after the other, keep flow. Emit from the builder itself. Put the dispatcher change on flowOn.
fun observeFeed(): Flow<List<Post>> = flow {
emit(cache.read())
emit(api.fetch())
}.flowOn(Dispatchers.IO)
The flowOn docs say it affects only the operators before it. The collector keeps its own context. When the dispatcher changes, a channel buffers values between the two coroutines. Android’s Kotlin flows guide gives the same advice. It says not to call emit from new coroutines or withContext blocks. In our run, the cached list arrived at about 300 ms. The fresh list followed at about 400 ms. Both were collected on main.
If the screen must show whichever load finishes first, use channelFlow. Its docs say its ProducerScope is safe to use from several coroutines at once. The direct translation looks like this.
fun observeFeed(): Flow<List<Post>> = channelFlow {
launch { send(cache.read()) }
launch { send(api.fetch()) }
}
It no longer crashes. Our run showed a new bug instead. The fresh list of 2 posts arrived at about 100 ms. The cached list of 1 post arrived at about 300 ms and replaced it. The screen ended on stale data. Concurrent producers have no order. So the code has to state which result wins. Our earlier post shows a combined StateFlow serving stale data for a different reason.
fun observeFeed(): Flow<List<Post>> = channelFlow {
val cached = launch { send(cache.read()) }
val fresh = api.fetch()
cached.cancel() // a cache read still in progress must not overwrite fresh data
send(fresh)
}
With the 300 ms cache, this version emitted only the fresh list, at about 100 ms. We then cut the cache delay to 50 ms. It emitted the cached list first and the fresh list at about 100 ms. That’s the order the screen wants in both cases. cache.read() and api.fetch() stay main-safe. Each one does its own withContext(Dispatchers.IO) inside, around the work and not around a send.
Walk the interviewer through the two messages in order
In a live debugging round, you may get the stack trace and the repository and nothing else. Our post on how the Android debugging round is scored covers the format. For this bug, answer in this order.
- Read the message. Two different contexts in “Flow was collected in” mean
emitran outside the collector’s context. - Point at the line. The
emitsits insidewithContext(Dispatchers.IO). - Name the rule.
flow { }preserves the collector’s context. OnlyflowOnchanges it, for the operators above it. - Give the sequential fix. Emit from the builder and add
.flowOn(Dispatchers.IO). - Get ahead of the follow-up. Launching the loads in parallel inside
flowfails the job check. Concurrent producers needchannelFlowandsend. - Name the ordering risk. With two producers, a slow cache can overwrite fresh data. Cancel the cache read when the network returns.
Step 5 answers the obvious next question about loading both in parallel. Raising it yourself shows you know the builder runs two separate checks.
Four fixes that keep the crash or hide a new bug
- “Add
.flowOn(Dispatchers.IO)and keep the launches.” Our repro still threw “Emission from another coroutine is detected”.flowOnchanges the context. It doesn’t merge two coroutines into one. - “Capture
currentCoroutineContext()and wrap eachemitinwithContextwith it.” The reporter of issue #2944, filed in September 2021, used this pattern. A maintainer called the error expected behavior and pointed tochannelFlow. In our run the hack still threw “Flow invariant is violated”. - “Wrap the
collectin try/catch.” The exception stops the flow at its first emit. Catching it shows an empty screen instead of a crash. - “Switch to
channelFlowand keep two plain launches.” The crash goes away. The stale-cache overwrite from the run above takes its place.