Skip to content
AppDues
Log in
Contact salesSign up

Kotlin Coroutine Bridges: Turning Callback APIs into Suspend Functions

Android's platform and many third-party SDKs still speak in callbacks: billing, location, Bluetooth, camera, preferences. Kotlin coroutines let you write sequential-looking code, but the bridge between the two worlds is not automatic. This guide walks through the bridge pattern end to end, from the single-value case to multi-value results, typed exception hierarchies, and the Result<T> alternative, with a clear rule for when a suspend bridge is the wrong tool.

Why callback chains resist composition

A billing flow that connects, queries products, purchases, and acknowledges can nest four or five callbacks deep. Each layer has its own error path, and failures do not travel upward in a structured way. The suspend equivalent reads top to bottom: connect, query, purchase, acknowledge. Each await call is a suspension point backed by a bridge that translates one callback into one resume.

The core bridge: suspend, register, resume once

Every bridge has three parts. First, suspendCancellableCoroutine pauses the coroutine and hands you a CancellableContinuation. Second, you call the callback-based API with an anonymous implementation that captures that continuation. Third, inside the callback you call resume or resumeWithException to deliver the outcome and unfreeze the coroutine. When the underlying API exposes teardown, register it through invokeOnCancellation so cancellation releases the resource instead of waiting on a callback that may never arrive.

The exactly-one-resume rule

A non-cancelled continuation must be resumed at most once. Zero resumes means the coroutine hangs until something outside cancels it. Two resumes on a live continuation throw IllegalStateException. After cancellation, resume is a safe no-op, so you do not need an isActive guard on every path, but every non-cancelled path through your callback must reach exactly one resume call.

Success and error callbacks: the two-path bridge

Most SDKs split callbacks into success and error methods, which maps cleanly onto resume and resumeWithException. When the success signature matches the continuation's expected type, a method reference such as continuation::resume is the cleanest form. The error path usually needs a wrapper because resumeWithException expects a Throwable while many SDKs expose a plain error object. Annotations such as @JvmSynthetic keep the suspend extension out of Java callers, and @Throws documents what the function can throw for interop and tooling.

Callback factories: removing interface boilerplate

Many Android APIs accept a typed callback interface rather than a lambda pair. Writing anonymous implementations inside every suspend function adds noise. Small factory functions convert an (onSuccess, onError) lambda pair into the specific interface the API expects. At scale this matters: a library with dozens of API surfaces ends up with a factory per callback shape, each doing one job.

Multi-value callbacks: wrapper classes

When a success callback delivers more than one value, a suspend function can only return one. Bundle the values in a data class and construct it in the success path. The purchase callback is a good example: success carries a transaction and updated customer info, while the error path carries an error plus a userCancelled flag. Both sides need a container or a richer exception to preserve that information.

Exception hierarchies: preserving error semantics

Wrapping every failure in a generic Exception(message) discards the structured error code callers need for programmatic handling. A better design wraps the original error object in a typed exception and exposes its code, so callers can branch on specific conditions. A subclass can add fields the callback carried, such as a cancellation flag, letting callers catch the broad type for all errors or the specific type when they need the extra detail.

The Result<T> variant: when exceptions are not the style you want

Some callers prefer kotlin.Result<T> over try/catch. A second variant of each bridge resumes with Result.success or Result.failure instead of throwing. From the coroutine's perspective the function always completes normally and returns a Result the caller unwraps with fold, onFailure, or mapCatching. The error object is still inside the failure, so the userCancelled flag and error code remain available. Offering both styles lets consumers choose without forcing one.

The lambda convenience layer

A middle layer between the raw interface and the suspend bridge accepts lambda pairs and converts them to the typed callback. The suspend extension then builds on that lambda extension. Each layer does one thing. Default error stubs let callers omit a handler for fire-and-forget operations, but silently swallowing errors is a common source of bugs, so use that convenience deliberately.

Worked example: bridging Google Play Billing

The acknowledgment API takes a purchase token and a callback that receives a BillingResult. The bridge builds the params, calls acknowledgePurchase, and resumes with whether the response code is OK. The consume API follows the same shape. The connection listener is subtler: onBillingSetupFinished delivers the setup result, while onBillingServiceDisconnected fires after a successful setup when the connection is later lost, not as an alternative during initial connection. That distinction is what lets a single resume call be correct here. If both methods could fire during setup, you would need extra state to guarantee exactly one resume.

Why suspendCancellableCoroutine is the default

suspendCoroutine hands you a plain Continuation with no knowledge of the Job that invoked it. When the parent is cancelled, the leaf does not participate: cancelAndJoin cannot complete, sibling failures cannot propagate past it, and the scope stays open waiting for a callback. The continuation retains the calling context, so lifecycle-scoped objects cannot be collected, and registered resources stay alive. suspendCancellableCoroutine participates in the Job graph. Parent cancellation resumes the continuation with a CancellationException, the leaf tears down, and the scope unwinds. The underlying callback may still fire later; resume on an already-cancelled continuation is a no-op. For callbacks you do not control, the upgrade is often a one-word rename, and cleanup can be added through invokeOnCancellation. Treat suspendCoroutine as a platform primitive rather than an application choice.

Applying the pattern beyond billing

The same structure works for location, preferences, and other callback APIs. A last-location call can attach success and failure listeners and resume accordingly; even without a cancellation hook, the bridge still tears down on cancellation and ignores the late callback. A preference change listener can register itself and unregister in invokeOnCancellation. What changes between APIs is the callback shape, how many values you capture, and whether cleanup is needed.

Three failure modes and how to tell them apart

Zero resumes: a code path never calls resume, so the coroutine suspends forever unless cancelled. This is common with multi-method listeners where one method might fire first. The fix is to make every path reach a resume, or wrap the bridge in withTimeout and guard with isActive. Double resume: a callback fires more than once, and the second resume throws IllegalStateException. If the callback is genuinely repeating, the suspend bridge is the wrong tool and callbackFlow is the right one, with awaitClose to unregister. Lost error type: wrapping failures in a generic Exception strips the structured code callers need. A typed exception that carries the original error object pays for itself whenever callers branch on specific conditions.

Choosing a bridge by callback shape
Callback shapeBridge primitiveReturn handlingError handlingCleanup
Single value, fires oncesuspendCancellableCoroutineresume(value)resumeWithException(typedException)invokeOnCancellation if teardown exists
Success and error methodssuspendCancellableCoroutineresume(value) or method referenceresumeWithException(wrapped error)invokeOnCancellation if teardown exists
Multiple success valuessuspendCancellableCoroutineresume(wrapper data class)resumeWithException(exception with extra fields)invokeOnCancellation if teardown exists
Non-throwing preferencesuspendCancellableCoroutineresume(Result.success(value))resume(Result.failure(typedException))invokeOnCancellation if teardown exists
Repeating or streamingcallbackFlowtrySend(value)close(cause) or emit errorawaitClose { unregister }

The decision table reflects the patterns described in the guide; it is not a benchmark of any specific SDK.

Frequently asked questions

Why should I avoid suspendCoroutine in application code?

Its continuation is not tied to coroutine cancellation. When a parent Job is cancelled, the leaf cannot tear down, so cancelAndJoin cannot complete, sibling failures cannot propagate, and the scope stays open holding references. suspendCancellableCoroutine participates in the Job graph and unwinds cleanly, even when the underlying callback has no cancellation support.

What happens if my callback never fires?

The coroutine suspends indefinitely unless something outside cancels it. Make sure every callback path reaches a resume call, or wrap the bridge in withTimeout and check isActive before resuming.

What if the callback fires twice?

The second resume on a live continuation throws IllegalStateException. If the callback is genuinely repeating, such as continuous location updates, use callbackFlow instead of a suspend bridge and unregister in awaitClose.

Should I expose both a throwing and a Result<T> version?

It is a reasonable choice when callers have different styles. The Result variant resumes with Result.failure instead of throwing, so the coroutine always completes normally, and the typed exception is still inside the failure for callers who need the error code or cancellation flag.