{"id":889,"date":"2026-10-23T13:52:00","date_gmt":"2026-10-23T11:52:00","guid":{"rendered":"https:\/\/grindloop.ai\/blog\/?p=889"},"modified":"2026-10-22T18:21:48","modified_gmt":"2026-10-22T16:21:48","slug":"flow-invariant-is-violated","status":"publish","type":"post","link":"https:\/\/grindloop.ai\/blog\/flow-invariant-is-violated\/","title":{"rendered":"Flow Invariant Is Violated: Why Emit Inside withContext or launch Crashes Kotlin Flow"},"content":{"rendered":"<p>&#8220;Flow invariant is violated&#8221; is an <code>IllegalStateException<\/code> from the <code>flow { }<\/code> builder. It means <code>emit<\/code> 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 <code>emit<\/code> inside <code>withContext(Dispatchers.IO)<\/code> gives the &#8220;Flow was collected in&#8221; message. It names two different contexts. Calling <code>emit<\/code> inside a <code>launch<\/code> gives &#8220;Emission from another coroutine is detected&#8221;. The first fix is to emit from the builder&#8217;s own coroutine and move the dispatcher change to <code>flowOn<\/code>. The second needs <code>channelFlow<\/code>, because <code>flow<\/code> doesn&#8217;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.<\/p>\n\n<h2>A feed repository that crashes the first time it leaves the main thread<\/h2>\n\n<p>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 <code>Dispatchers.IO<\/code>. This is the change that shipped.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class FeedRepository(private val cache: FeedCache, private val api: FeedApi) {\n    fun observeFeed(): Flow&lt;List&lt;Post&gt;&gt; = flow {\n        withContext(Dispatchers.IO) {\n            emit(cache.read())\n        }\n        emit(api.fetch())\n    }\n}<\/pre>\n\n\n<p>The screen collects this in <code>viewModelScope<\/code>. The first emit throws before any post reaches the UI.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">java.lang.IllegalStateException: Flow invariant is violated:\n    Flow was collected in [BlockingCoroutine{Active}@11cf7de2, BlockingEventLoop@17f67224],\n    but emission happened in [DispatchedCoroutine{Active}@18f95425, Dispatchers.IO].\n    Please refer to 'flow' documentation or use 'flowOn' instead<\/pre>\n\n\n<p>That output comes from our repro, so the collector is <code>runBlocking<\/code>. In an app, the first bracket names the ViewModel&#8217;s coroutine and its main dispatcher. The second bracket names the context that called <code>emit<\/code>.<\/p>\n\n<h2>Cause one: flow invariant is violated when emit leaves the collector&#8217;s context<\/h2>\n\n<p>A cold flow runs its builder inside the collector&#8217;s coroutine. The <a href=\"https:\/\/kotlinlang.org\/api\/kotlinx.coroutines\/kotlinx-coroutines-core\/kotlinx.coroutines.flow\/-flow\/\" target=\"_blank\" rel=\"noopener\"><code>Flow<\/code> interface docs<\/a> call this context preservation. A flow keeps its execution context to itself. It never leaks that context to downstream operators. The docs name <code>flowOn<\/code> as the only way to change a flow&#8217;s context. Their sample marks <code>withContext<\/code> around <code>emit<\/code> as prohibited.<\/p>\n\n<p>The rule protects the collector. Code inside <code>collect { }<\/code> assumes it runs where it was called. In a ViewModel, that&#8217;s the main thread. If <code>emit<\/code> 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 <code>emit<\/code>. It compares the current context with the collector&#8217;s context. Any mismatch throws the message above.<\/p>\n\n<p>The reviewer&#8217;s goal was fine. Only the placement was wrong. <code>withContext<\/code> around the read is allowed, because the read returns a value. The emit then runs back in the collector&#8217;s context. Our run of <code>flow { emit(withContext(Dispatchers.IO) { ... }) }<\/code> did the read on a <code>DefaultDispatcher-worker<\/code> thread. It collected on <code>main<\/code> without an error. The bug is <code>withContext<\/code> around <code>emit<\/code>.<\/p>\n\n<h2>Cause two: launch inside flow { } emits from another coroutine<\/h2>\n\n<p>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.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">fun observeFeed(): Flow&lt;List&lt;Post&gt;&gt; = flow {\n    coroutineScope {\n        launch { emit(cache.read()) }\n        launch { emit(api.fetch()) }\n    }\n}<\/pre>\n\n\n<p>Neither <code>launch<\/code> changes the dispatcher. It still crashes, with a different message.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">java.lang.IllegalStateException: Flow invariant is violated:\n    Emission from another coroutine is detected.\n    Child of StandaloneCoroutine{Active}@e50a6f6, expected child of BlockingCoroutine{Active}@11cf7de2.\n    FlowCollector is not thread-safe and concurrent emissions are prohibited.\n    To mitigate this restriction please use 'channelFlow' builder instead of 'flow'<\/pre>\n\n\n<p>This check looks at the <code>Job<\/code>, not the thread. A <code>launch<\/code> creates a new coroutine with its own job. Two of them can call <code>emit<\/code> at the same time. A <code>FlowCollector<\/code> has no locking, so the builder rejects any emit from a child coroutine. The maintainers chose this in <a href=\"https:\/\/github.com\/Kotlin\/kotlinx.coroutines\/issues\/1210\" target=\"_blank\" rel=\"noopener\">kotlinx.coroutines issue #1210<\/a>, filed in May 2019. They kept the collector non-thread-safe for speed. They added <code>channelFlow<\/code> for concurrent producers. Those call <code>send<\/code> instead of <code>emit<\/code>.<\/p>\n\n<p>We ran four versions of the repository with <code>kotlinc<\/code> 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 <code>withContext<\/code> version and the <code>launch<\/code> version printed the two messages above. Adding <code>.flowOn(Dispatchers.IO)<\/code> to the <code>launch<\/code> version still threw &#8220;Emission from another coroutine is detected&#8221;. <code>flowOn<\/code> moves the whole builder to another context. The two launches are still separate coroutines inside it.<\/p>\n\n<h2>The fix depends on whether the two loads must run at the same time<\/h2>\n\n<p>If the cache and the network can run one after the other, keep <code>flow<\/code>. Emit from the builder itself. Put the dispatcher change on <code>flowOn<\/code>.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">fun observeFeed(): Flow&lt;List&lt;Post&gt;&gt; = flow {\n    emit(cache.read())\n    emit(api.fetch())\n}.flowOn(Dispatchers.IO)<\/pre>\n\n\n<p>The <a href=\"https:\/\/kotlinlang.org\/api\/kotlinx.coroutines\/kotlinx-coroutines-core\/kotlinx.coroutines.flow\/flow-on.html\" target=\"_blank\" rel=\"noopener\"><code>flowOn<\/code> docs<\/a> 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&#8217;s <a href=\"https:\/\/developer.android.com\/kotlin\/flow\" target=\"_blank\" rel=\"noopener\">Kotlin flows guide<\/a> gives the same advice. It says not to call <code>emit<\/code> from new coroutines or <code>withContext<\/code> blocks. In our run, the cached list arrived at about 300 ms. The fresh list followed at about 400 ms. Both were collected on <code>main<\/code>.<\/p>\n\n<p>If the screen must show whichever load finishes first, use <code>channelFlow<\/code>. Its <a href=\"https:\/\/kotlinlang.org\/api\/kotlinx.coroutines\/kotlinx-coroutines-core\/kotlinx.coroutines.flow\/channel-flow.html\" target=\"_blank\" rel=\"noopener\">docs<\/a> say its <code>ProducerScope<\/code> is safe to use from several coroutines at once. The direct translation looks like this.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">fun observeFeed(): Flow&lt;List&lt;Post&gt;&gt; = channelFlow {\n    launch { send(cache.read()) }\n    launch { send(api.fetch()) }\n}<\/pre>\n\n\n<p>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 <a href=\"https:\/\/grindloop.ai\/blog\/why-your-combined-stateflow-shows-stale-data-sharingstarted-lazily-vs-eagerly\/\">combined StateFlow serving stale data<\/a> for a different reason.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">fun observeFeed(): Flow&lt;List&lt;Post&gt;&gt; = channelFlow {\n    val cached = launch { send(cache.read()) }\n    val fresh = api.fetch()\n    cached.cancel() \/\/ a cache read still in progress must not overwrite fresh data\n    send(fresh)\n}<\/pre>\n\n\n<p>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&#8217;s the order the screen wants in both cases. <code>cache.read()<\/code> and <code>api.fetch()<\/code> stay main-safe. Each one does its own <code>withContext(Dispatchers.IO)<\/code> inside, around the work and not around a <code>send<\/code>.<\/p>\n\n<h2>Walk the interviewer through the two messages in order<\/h2>\n\n<p>In a live debugging round, you may get the stack trace and the repository and nothing else. Our post on <a href=\"https:\/\/grindloop.ai\/blog\/android-debugging-interview-second-bug\/\">how the Android debugging round is scored<\/a> covers the format. For this bug, answer in this order.<\/p>\n\n<ol>\n<li>Read the message. Two different contexts in &#8220;Flow was collected in&#8221; mean <code>emit<\/code> ran outside the collector&#8217;s context.<\/li>\n<li>Point at the line. The <code>emit<\/code> sits inside <code>withContext(Dispatchers.IO)<\/code>.<\/li>\n<li>Name the rule. <code>flow { }<\/code> preserves the collector&#8217;s context. Only <code>flowOn<\/code> changes it, for the operators above it.<\/li>\n<li>Give the sequential fix. Emit from the builder and add <code>.flowOn(Dispatchers.IO)<\/code>.<\/li>\n<li>Get ahead of the follow-up. Launching the loads in parallel inside <code>flow<\/code> fails the job check. Concurrent producers need <code>channelFlow<\/code> and <code>send<\/code>.<\/li>\n<li>Name the ordering risk. With two producers, a slow cache can overwrite fresh data. Cancel the cache read when the network returns.<\/li>\n<\/ol>\n\n<p>Step 5 answers the obvious next question about loading both in parallel. Raising it yourself shows you know the builder runs two separate checks.<\/p>\n\n<h2>Four fixes that keep the crash or hide a new bug<\/h2>\n\n<ul>\n<li>&#8220;Add <code>.flowOn(Dispatchers.IO)<\/code> and keep the launches.&#8221; Our repro still threw &#8220;Emission from another coroutine is detected&#8221;. <code>flowOn<\/code> changes the context. It doesn&#8217;t merge two coroutines into one.<\/li>\n<li>&#8220;Capture <code>currentCoroutineContext()<\/code> and wrap each <code>emit<\/code> in <code>withContext<\/code> with it.&#8221; The reporter of <a href=\"https:\/\/github.com\/Kotlin\/kotlinx.coroutines\/issues\/2944\" target=\"_blank\" rel=\"noopener\">issue #2944<\/a>, filed in September 2021, used this pattern. A maintainer called the error expected behavior and pointed to <code>channelFlow<\/code>. In our run the hack still threw &#8220;Flow invariant is violated&#8221;.<\/li>\n<li>&#8220;Wrap the <code>collect<\/code> in try\/catch.&#8221; The exception stops the flow at its first emit. Catching it shows an empty screen instead of a crash.<\/li>\n<li>&#8220;Switch to <code>channelFlow<\/code> and keep two plain launches.&#8221; The crash goes away. The stale-cache overwrite from the run above takes its place.<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Flow invariant is violated means emit ran outside the collector&#8217;s context. Why withContext and launch both trip it, plus the flowOn and channelFlow fixes.<\/p>\n","protected":false},"author":2,"featured_media":892,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"Flow Invariant Is Violated: Why Emit Inside withContext or launch Crashes Kotlin Flow","rank_math_description":"Flow invariant is violated means emit ran outside the collector's context. Why withContext and launch both trip it, plus the flowOn and channelFlow fixes.","rank_math_focus_keyword":"flow invariant is violated","footnotes":""},"categories":[9,3],"tags":[15,13,16,12,110,45],"class_list":["post-889","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-bug-squash","category-coroutines","tag-android","tag-coroutines","tag-interview-prep","tag-kotlin","tag-kotlin-flow","tag-technical-interview"],"_links":{"self":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/889","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/comments?post=889"}],"version-history":[{"count":2,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/889\/revisions"}],"predecessor-version":[{"id":891,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/889\/revisions\/891"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media\/892"}],"wp:attachment":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media?parent=889"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/categories?post=889"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/tags?post=889"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}