dhmitchell

dhmitchell

Kotlin Coroutine Confidence: asynchronous read file

In “gallery/v14/src/main/kotlin/com/example/gallery/GetImageFromFile.kt”

  • won’t the .use always call channel.close() on exit? if so, why do you need invokeOnCancellation? or does cancellation somehow avoid the finally in the use?
  • if I wanted to iterate through the file line by line, I presume I’d call readline rather than read and otherwise it’s roughly the same?

Marked As Solved

sam-cooper

sam-cooper

Author of Kotlin Coroutine Confidence

Yes, since the use() block wraps the entire call to suspendCancellableCoroutine(), it will always close the AsynchronousFileChannel when suspendCancellableCoroutine() exits for any reason. The problem is that without that invokeOnCancellation() block, suspendCancellableCoroutine() will not exit—at least, not until we’ve finished reading the entire file.

What we’re trying to do by adding invokeOnCancellation() is to ensure that we can stop the file operation before it finishes. When the coroutine is cancelled, Kotlin executes the invokeOnCancellation() block. Calling channel.close() inside the block is how we interrupt the ongoing file operation and cause it to end early.

That means there are two different ways the file can be closed:

  1. The read() operation ends on its own, either because it reached the end of the file or because it ran into an I/O error. The suspension point resumes, and the coroutine exits the use() block, closing the channel in the process.
  2. The user cancels the coroutine before read() is done. This triggers invokeOnCancellation(), which in turn calls channel.close(). This fires the read() operation’s failed() callback, allowing the coroutine to resume from its suspended state without waiting for the rest of the data. Again, it exits the use() block, but the file channel is already closed, so that’s a no-op.

I’ll see what I can do to make all this clearer in the book! Although it’s not something you’re likely to have to deal with often, I’d like to make sure it’s clear.

As for the second question, that’s a little trickier. The AsynchronousFileChannel just deals with raw byte data, and it doesn’t have any methods for working with text or line separators. Unfortunately that means there’s no readLine() function. You could write one of your own, but you’d need to include logic to buffer the data in chunks, inspect it for line separators, and so on.

In a real application, it’s likely that the more complete feature set of the java.io libraries will outweigh any asynchronous advantage from using java.nio. If I needed to read lines from a text file, I’d probably just use a good old fashioned Reader, and accept the minor cost of a blocked IO thread. In the book, I’m not intending to advocate for using AsynchronousFileChannel all over the place—it’s just meant as a handy example of a simple (ish) operation that we can use to illustrate asynchronous callbacks. Perhaps I’ll add a quick note to that effect in the text, too.

Phew! With any luck, I’ll find a way to say all this in the book using slightly fewer words. Thanks for asking these questions—they all help me to make the explanations in the book clearer.

Popular Pragmatic Bookshelf topics Top

jimschubert
In Chapter 3, the source for index introduces Config on page 31, followed by more code including tests; Config isn’t introduced until pag...
New
jon
Some minor things in the paper edition that says “3 2020” on the title page verso, not mentioned in the book’s errata online: p. 186 But...
New
Razor54672
The answer to 3rd Problem of Chapter 5 (Making Choices) of “Practical Programming, Third Edition” seems incorrect in the given answer ke...
New
yulkin
your book suggests to use Image.toByteData() to convert image to bytes, however I get the following error: "the getter ‘toByteData’ isn’t...
New
sdmoralesma
Title: Web Development with Clojure, Third Edition - migrations/create not working: p159 When I execute the command: user=> (create-...
New
mikecargal
Title: Hands-On Rust (Chapter 11: prefab) Just played a couple of amulet-less games. With a bit of debugging, I believe that your can_p...
New
Mmm
Hi, build fails on: bracket-lib = “~0.8.1” when running on Mac Mini M1 Rust version 1.5.0: Compiling winit v0.22.2 error[E0308]: mi...
New
HarryDeveloper
Hi @venkats, It has been mentioned in the description of ‘Supervisory Job’ title that 2 things as mentioned below result in the same eff...
New
jskubick
I found an issue in Chapter 7 regarding android:backgroundTint vs app:backgroundTint. How to replicate: load chapter-7 from zipfile i...
New
digitalbias
Title: Build a Weather Station with Elixir and Nerves: Problem connecting to Postgres with Grafana on (page 64) If you follow the defau...
New

Other popular topics Top

Exadra37
I am thinking in building or buy a desktop computer for programing, both professionally and on my free time, and my choice of OS is Linux...
New
brentjanderson
Bought the Moonlander mechanical keyboard. Cherry Brown MX switches. Arms and wrists have been hurting enough that it’s time I did someth...
New
foxtrottwist
Here’s our thread for the Keyboardio Atreus. It is a mechanical keyboard based on and a slight update of the original Atreus (Keyboardio ...
New
AstonJ
This looks like a stunning keycap set :orange_heart: A LEGENDARY KEYBOARD LIVES ON When you bought an Apple Macintosh computer in the e...
New
AstonJ
We’ve talked about his book briefly here but it is quickly becoming obsolete - so he’s decided to create a series of 7 podcasts, the firs...
New
PragmaticBookshelf
Author Spotlight James Stanier @jstanier James Stanier, author of Effective Remote Work , discusses how to rethink the office as we e...
New
PragmaticBookshelf
Rails 7 completely redefines what it means to produce fantastic user experiences and provides a way to achieve all the benefits of single...
New
PragmaticBookshelf
Build efficient applications that exploit the unique benefits of a pure functional language, learning from an engineer who uses Haskell t...
New
First poster: joeb
The File System Access API with Origin Private File System. WebKit supports new API that makes it possible for web apps to create, open,...
New
DevotionGeo
I have always used antique keyboards like Cherry MX 1800 or Cherry MX 8100 and almost always have modified the switches in some way, like...
New

Latest in Kotlin Coroutine Confidence