Search code examples
kotlinkotlinx.coroutines

Kotlin - How to read from file asynchronously?


Is there any kotlin idiomatic way to read a file content's asynchronously? I couldn't find anything in documentation.


Solution

  • A least as of Java 7 (which is where Android is stuck), there isn't any API that would tap into the low-level async file IO support (like io_uring). There is a class called AsynchronousFileChannel, but, as its docs state,

    An AsynchronousFileChannel is associated with a thread pool to which tasks are submitted to handle I/O events and dispatch to completion handlers that consume the results of I/O operations on the channel.

    That makes it no better than the following, bog-standard Kotlin idiom:

    launch {
        val contents = withContext(Dispatchers.IO) {
            FileInputStream("filename.txt").use { it.readBytes() }
        }
        processContents(contents)
    }
    go_on_with_other_stuff_while_file_is_loading()
    

    This uses Kotlin's own dedicated IO thread pool and unblocks the UI thread. If you're on Android, that is your actual concern, anyway.