{"id":1108,"date":"2026-12-01T13:49:00","date_gmt":"2026-12-01T12:49:00","guid":{"rendered":"https:\/\/grindloop.ai\/blog\/?p=1108"},"modified":"2026-11-30T21:42:06","modified_gmt":"2026-11-30T20:42:06","slug":"illegalstateexception-already-resumed","status":"publish","type":"post","link":"https:\/\/grindloop.ai\/blog\/illegalstateexception-already-resumed\/","title":{"rendered":"IllegalStateException: Already Resumed, but Proposed With Update: Why a Kotlin Location Wrapper Crashes on the Second Fix"},"content":{"rendered":"<p>IllegalStateException: Already resumed means a <code>suspendCancellableCoroutine<\/code> got a second <code>resume<\/code>. The continuation inside it takes exactly one value. The usual trigger is a callback that fires more than once. A location wrapper shows it well. You wrap <code>requestLocationUpdates<\/code> to get one fix. Then you resume on every <code>onLocationResult<\/code>. The first fix returns. The second one crashes the app on the main thread. Two causes stack here. The callback is multi-shot while the continuation is single-shot. The wrapper also never removes the callback, so it keeps firing after the coroutine is done. That second cause also breaks the cancel path. If the screen closes first, the first late fix is ignored and the next one crashes. The fix is <code>callbackFlow<\/code> with <code>awaitClose<\/code>, then <code>first()<\/code>. The flow removes the callback when collection stops. Guarding the resume with <code>isActive<\/code> only hides the crash.<\/p>\n\n<h2>A current-location wrapper that crashes on the second fix<\/h2>\n\n<p>A store-finder screen needs the user&#8217;s position once. The repository wraps the fused location client in a suspend function. It looks like the one-shot examples in the docs. But it calls the streaming API.<\/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 LocationRepository(private val client: FusedLocationProviderClient) {\n\n    @SuppressLint(\"MissingPermission\")\n    suspend fun currentLocation(): Location =\n        suspendCancellableCoroutine { cont -&gt;\n            val request = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 1_000).build()\n            val callback = object : LocationCallback() {\n                override fun onLocationResult(result: LocationResult) {\n                    result.lastLocation?.let { cont.resume(it) }\n                }\n            }\n            client.requestLocationUpdates(request, callback, Looper.getMainLooper())\n        }\n}<\/pre>\n\n\n<p>Android&#8217;s <a href=\"https:\/\/developer.android.com\/develop\/sensors-and-location\/location\/request-updates\" target=\"_blank\" rel=\"noopener\">request location updates guide<\/a> describes this API as a stream. The provider calls <code>onLocationResult()<\/code> again for each update. Updates stop only when you call <code>removeLocationUpdates()<\/code> with the same callback. Nothing in this wrapper does that.<\/p>\n\n<p>We rebuilt the wrapper in plain Kotlin and ran it with Kotlin 2.4.20 and kotlinx.coroutines 1.11.0. A fake client pushes a fix every 100 ms on its own thread until the listener is removed. It prints any exception a listener throws. The first call ran to the end. A second call was cancelled after 20 ms, before its first fix arrived.<\/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=\"\">got Fix(lat=52.52, lng=13.4, accuracyM=200)\nCRASH on callback thread: java.lang.IllegalStateException: Already resumed, but proposed with update Fix(lat=52.52, lng=13.4, accuracyM=100)\nCRASH on callback thread: java.lang.IllegalStateException: Already resumed, but proposed with update Fix(lat=52.52, lng=13.4, accuracyM=66)\nlisteners still registered: 1\n...\nlisteners still registered: 2<\/pre>\n\n\n<p>The caller got its first fix. Every later fix threw on the callback thread. In the app that thread is the main looper, so the first throw kills the process. The stack trace points into the location callback, not into your coroutine. That is why the crash looks unrelated to the code that called <code>currentLocation()<\/code>.<\/p>\n\n<h2>Already resumed means one continuation got a second value from a stream<\/h2>\n\n<p>The <a href=\"https:\/\/kotlinlang.org\/api\/kotlinx.coroutines\/kotlinx-coroutines-core\/kotlinx.coroutines\/suspend-cancellable-coroutine.html\" target=\"_blank\" rel=\"noopener\">suspendCancellableCoroutine documentation<\/a> says it is for a single-shot callback API. For multi-shot callback APIs it points to <code>callbackFlow<\/code>. The <a href=\"https:\/\/github.com\/Kotlin\/kotlinx.coroutines\/blob\/master\/kotlinx-coroutines-core\/common\/src\/CancellableContinuation.kt\" target=\"_blank\" rel=\"noopener\">CancellableContinuation source<\/a> draws the states. A continuation goes from active to resumed or to cancelled. It never goes back. The same file says concurrent resume calls throw IllegalStateException and count as a programming error.<\/p>\n\n<p>The message comes from <code>resumeImpl<\/code> in <a href=\"https:\/\/github.com\/Kotlin\/kotlinx.coroutines\/blob\/master\/kotlinx-coroutines-core\/common\/src\/CancellableContinuationImpl.kt\" target=\"_blank\" rel=\"noopener\">CancellableContinuationImpl<\/a>. Once the state is resumed, any further <code>resume<\/code> calls <code>alreadyResumedError<\/code>. That function builds the message <code>Already resumed, but proposed with update<\/code> plus the rejected value. So the value in the message is the rejected extra fix. It tells you which callback fired twice.<\/p>\n\n<p>A test fake that returns one value per call never fires twice, so tests can miss this. The fused provider keeps calling back for as long as the request stays registered.<\/p>\n\n<h2>A callback that is never removed crashes after the screen closes<\/h2>\n\n<p>The second cause is the missing <code>removeLocationUpdates()<\/code>. The docs example for <code>suspendCancellableCoroutine<\/code> unregisters in <code>invokeOnCancellation<\/code>. This wrapper has no cleanup on any path. So the callback outlives the coroutine on both the success path and the cancel path.<\/p>\n\n<p>The cancel path behaves differently. <code>resumeImpl<\/code> ignores a resume on a cancelled continuation, because cancellation can race with a callback. But it ignores only one. The <code>CancelledContinuation<\/code> state flips a <code>resumed<\/code> flag on the first late call. The second late call falls through to the same <code>alreadyResumedError<\/code>. Our cancelled call showed exactly that. The first fix after the cancel was dropped silently. Every fix after it threw.<\/p>\n\n<p>So a user who opens the store finder and backs out at once still crashes. It just happens about two fixes later, on a different screen. The repro also showed the cost before any crash. Registered listeners went from one to two. Each one keeps GPS requests running and holds the continuation, so the coroutine&#8217;s frame stays reachable too.<\/p>\n\n<h2>The fix is callbackFlow with awaitClose, then first()<\/h2>\n\n<p>Model the API as what it is, a stream. <code>callbackFlow<\/code> gives you a channel that accepts many values. <code>awaitClose<\/code> runs when the collector stops for any reason. The <a href=\"https:\/\/kotlinlang.org\/api\/kotlinx.coroutines\/kotlinx-coroutines-core\/kotlinx.coroutines.flow\/callback-flow.html\" target=\"_blank\" rel=\"noopener\">callbackFlow documentation<\/a> calls <code>awaitClose<\/code> mandatory to prevent leaks. It throws IllegalStateException if the block returns while the channel is still open. A one-shot read then becomes <code>first()<\/code> on that stream.<\/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 LocationRepository(private val client: FusedLocationProviderClient) {\n\n    @SuppressLint(\"MissingPermission\")\n    fun locationUpdates(intervalMs: Long = 1_000): Flow&lt;Location&gt; = callbackFlow {\n        val request = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, intervalMs).build()\n        val callback = object : LocationCallback() {\n            override fun onLocationResult(result: LocationResult) {\n                result.lastLocation?.let { trySend(it) }\n            }\n        }\n        client.requestLocationUpdates(request, callback, Looper.getMainLooper())\n        awaitClose { client.removeLocationUpdates(callback) }\n    }.buffer(Channel.CONFLATED)\n\n    suspend fun currentLocation(): Location = locationUpdates().first()\n}<\/pre>\n\n\n<p><code>first()<\/code> takes one value and then cancels the flow. That cancellation runs <code>awaitClose<\/code>. The <code>awaitClose<\/code> block removes the callback. A cancelled caller takes the same path. <code>trySend<\/code> never throws into the provider&#8217;s thread. It returns a failed result once the channel is closed. With a slow collector, the conflated buffer keeps only the newest fix. For location that is what you want. The callbackFlow docs list <code>buffer(Channel.CONFLATED)<\/code> as one way to avoid overfilling the default buffer.<\/p>\n\n<p>We ran the same harness against the plain-Kotlin version of this code.<\/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=\"\">got Fix(lat=52.52, lng=13.4, accuracyM=200)\nlisteners still registered: 0\nlisteners still registered: 0\nfirst fix within 50 m: Fix(lat=52.52, lng=13.4, accuracyM=28)\nlisteners still registered: 0<\/pre>\n\n\n<p>Neither path crashed. No listener was left behind. The stream also supports a filtered one-shot read. <code>first { it.accuracy &lt;= 50f }<\/code> waits for a usable fix and still cleans up. The plain-Kotlin version filtered on its own accuracy field. The Android code above was not compiled here, because the Play services classes need an Android project.<\/p>\n\n<p>If you want just a cached or single fresh fix, the fused client has one-shot calls. Android&#8217;s <a href=\"https:\/\/developer.android.com\/develop\/sensors-and-location\/location\/retrieve-current\" target=\"_blank\" rel=\"noopener\">get the last known location guide<\/a> covers them. Those suit <code>suspendCancellableCoroutine<\/code>, because each call answers once.<\/p>\n\n<h2>How to explain the crash in a technical round<\/h2>\n\n<p>An interviewer may show the first snippet and a crash report from the main thread. Walk from the message to both causes.<\/p>\n\n<ol>\n<li>Read the message. &#8220;Already resumed&#8221; means a second <code>resume<\/code> on one continuation. The value in it is the extra one.<\/li>\n<li>Name the first cause. <code>requestLocationUpdates<\/code> calls back for every update. The continuation takes one value.<\/li>\n<li>Name the second cause. Nothing calls <code>removeLocationUpdates()<\/code>, on success or on cancel.<\/li>\n<li>Explain the cancel case. A cancelled continuation ignores one late resume, then throws on the next. Leaving the screen early still crashes.<\/li>\n<li>Give the fix. Use <code>callbackFlow<\/code> with <code>awaitClose { removeLocationUpdates(callback) }<\/code>. Call <code>first()<\/code> for one value.<\/li>\n<li>Name the rule behind it. <code>suspendCancellableCoroutine<\/code> is for single-shot callbacks. <code>callbackFlow<\/code> is for multi-shot ones.<\/li>\n<\/ol>\n\n<p>Step 4 shows you read the continuation&#8217;s state machine as well as the stack trace. Hass explains what a debugging round scores after the first fix in <a href=\"https:\/\/grindloop.ai\/blog\/android-debugging-interview-second-bug\/\">his debugging interview post<\/a>. A related cancellation trap is in our post on <a href=\"https:\/\/grindloop.ai\/blog\/runcatching-swallows-cancellationexception\/\">runCatching swallowing CancellationException<\/a>.<\/p>\n\n<h2>Answers that hide the crash and keep the leak<\/h2>\n\n<p>&#8220;Check <code>if (cont.isActive)<\/code> before resuming.&#8221; The crash goes away. We ran it. No exception printed. But the listener count still went from one to two. GPS keeps running for every call. The CancellableContinuation docs also warn that <code>isActive<\/code> can change right after you read it. A callback on another thread can still slip a second resume past the check.<\/p>\n\n<p>&#8220;Wrap the resume in <code>try<\/code>\/<code>catch<\/code>.&#8221; That catches the symptom on every fix, for as long as updates run. The updates and the leak stay.<\/p>\n\n<p>&#8220;Call <code>removeLocationUpdates()<\/code> inside <code>onLocationResult<\/code>.&#8221; This fixes the success path. The cancel path still never unregisters, so a user who leaves early still leaks a request. You would also need <code>invokeOnCancellation<\/code> and a guard for an update already in flight. <code>callbackFlow<\/code> handles all three in one place.<\/p>\n\n<p>&#8220;Use <code>tryResume<\/code>.&#8221; The CancellableContinuation source marks it <code>@InternalCoroutinesApi<\/code>. It is not meant for app code. It also leaves the callback registered.<\/p>","protected":false},"excerpt":{"rendered":"<p>Already resumed means suspendCancellableCoroutine got a second resume from a multi-shot callback. Runnable repro, the callbackFlow fix and wrong answers.<\/p>\n","protected":false},"author":2,"featured_media":1111,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"IllegalStateException: Already Resumed, but Proposed With Update: Why a Kotlin Location Wrapper Crashes","rank_math_description":"Already resumed means suspendCancellableCoroutine got a second resume from a multi-shot callback. Runnable repro, the callbackFlow fix and wrong answers.","rank_math_focus_keyword":"already resumed","footnotes":""},"categories":[9,3],"tags":[15,124,13,87,16,12,110,45],"class_list":["post-1108","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-bug-squash","category-coroutines","tag-android","tag-callbackflow","tag-coroutines","tag-debugging-interview","tag-interview-prep","tag-kotlin","tag-kotlin-flow","tag-technical-interview"],"_links":{"self":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/1108","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=1108"}],"version-history":[{"count":1,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/1108\/revisions"}],"predecessor-version":[{"id":1112,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/1108\/revisions\/1112"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media\/1111"}],"wp:attachment":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media?parent=1108"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/categories?post=1108"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/tags?post=1108"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}