The decision
A new query cancels the previous search. Check that the request is active before starting its read and again before returning any result. A live request may use its cached value after an IOException, including a socket timeout. A cancelled request can also report IOException when its socket closes.
Read the Kotlin
Follow cancellation through the recovery branch
Cancellation can reach a suspended read as CancellationException. runCatching also catches that exception. An unconditional getOrElse can turn it into cached data, and an ordinary call to publish can then run. A cancelled transport can also report IOException. After recovering from I/O, check the current Job before returning data to the caller.
val data = try { read() } catch (e: IOException) { cache }
currentCoroutineContext().ensureActive()
return dataBound the work between checkpoints
Cancelling a Job records a request. A CPU loop can keep running until it reaches a cancellation check. Place ensureActive() at the start of each bounded unit of work. If cancellation arrives during one tile, that tile may finish, but the next one checks before starting. A check only at the end could waste the rest of the batch.
for (tile in tiles) {
currentCoroutineContext().ensureActive()
decode(tile)
}Recover only from the failures the cache can replace
A live request might time out while its Job remains active. SocketTimeoutException is an IOException, so an I/O catch can supply the cache in that case. A parser’s NumberFormatException or IllegalStateException signals a different problem. Catching Exception also catches those failures and can turn a broken parser into an apparently successful response.
The full example
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.concurrent.CancellationException;
import java.util.function.BooleanSupplier;
class Lesson {
interface Lookup {
String fetch() throws IOException;
}
static void checkActive(BooleanSupplier cancelled) {
if (cancelled.getAsBoolean()) throw new CancellationException();
}
static String preview(String cached, BooleanSupplier cancelled, Lookup load) {
checkActive(cancelled);
String result;
try {
result = load.fetch();
} catch (IOException offline) {
result = cached;
}
checkActive(cancelled);
return result;
}
}import java.io.IOException
import kotlinx.coroutines.*
suspend fun preview(
cached: String,
load: suspend () -> String
): String {
currentCoroutineContext().ensureActive()
val result = try {
load()
} catch (offline: IOException) {
cached
}
currentCoroutineContext().ensureActive()
return result
}Inputs and outcomes
| Input | Outcome | Why it matters |
|---|---|---|
A live search returns "new" | new | The second checkpoint sees an active request and lets the result through. |
An active read throws SocketTimeoutException | cached result | A socket timeout is an IOException. Its class alone tells us nothing about the search Job. |
The search is cancelled. Closing its socket makes the adapter throw IOException. | Cancellation propagates | The catch selects cached text, then the checkpoint observes the cancelled Job before the caller can publish that text. |
One child is suspended in delay(100) when its owner calls request.cancelAndJoin(). | The child exits its delay and runs its finally block before the owner continues. | launch returns the child Job. cancelAndJoin requests cancellation and suspends the owner until the child finishes. |
Walk through the code
- A suspend function can pause its caller and resume later. For example, delay(100) suspends a coroutine while its thread can run other work. Calling a suspend function directly keeps the same coroutine. Ordinary CPU instructions can continue in a cancelled Job until a checkpoint observes cancellation.
- Start with one child inside coroutineScope: val request = launch { delay(100); publish("ready") }. The scope owns this child. If the owner calls request.cancelAndJoin() while the child is suspended in delay, cancellation skips publish and the owner waits for the child’s cleanup.
- preview runs load in the request coroutine. ensureActive() checks that coroutine’s Job at entry and immediately before return. The Java version gets the equivalent request state from a cancellation token. Both catch only IOException and let other exceptions propagate.
- A socket read timeout can occur while the request is active. A closed socket can report IOException after the request was cancelled. Checking the Job after either outcome decides whether the result can leave preview.
The Java habit
runCatching { load() }.getOrElse { cached } catches Throwable, which includes CancellationException. In an already cancelled coroutine, ordinary non-suspending lines can still run after that accidental recovery.
When to choose differently
The final checkpoint observes cancellation at that instant. If requests can be replaced concurrently with publication, the screen must also verify the current request ID when it commits a result. Stopping a blocking socket read promptly requires support from the I/O adapter.