I am wondering how to do something like that with ...
# coroutines
d
I am wondering how to do something like that with coroutines:
Copy code
internal class ExampleWalker(val events : Channel<Path>) : SimpleFileVisitor<Path>() {
    override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
        events.send(file)
        return FileVisitResult.CONTINUE
    }
}

fun main() = runBlocking {
    val events = Channel<Path>()
    Files.walkFileTree(Paths.get("/tmp"), ExampleWalker(events))
}
Obviously, it does not work like that because
visitFile(...)
is not a suspend function. But I can't make it a suspend function because it is derived from
SimpleFileVisitor
(which I can't change). What is the way to go?
e
it's going to block so the best you can do is punt it into another thread if you want to consume it from a channel
👍 1
if it's about file walking specifically and not these types of callbacks in general though, https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.io.path/walk.html
d
It is a bit of both (path traversal and how to deal with legacy non suspending APIs). Thank you for your help!
k
You could also make a channel with an unlimited buffer and
trySend
every element.
d
Wow, I have not seen that in a long time.
Copy code
directory.walk(PathWalkOption.INCLUDE_DIRECTORIES, PathWalkOption.BREADTH_FIRST).forEach { path ->
    println(path)
}
Results in
Copy code
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x0000000105a6111c, pid=78801, tid=33539
#
# JRE version: OpenJDK Runtime Environment Homebrew (11.0.25) (build 11.0.25+0)
# Java VM: OpenJDK 64-Bit Server VM Homebrew (11.0.25+0, mixed mode, tiered, compressed oops, g1 gc, bsd-aarch64)
# Problematic frame:
# V  [libjvm.dylib+0x69511c]  ObjectSynchronizer::inflate(Thread*, oopDesc*, ObjectSynchronizer::InflateCause)+0x18c
#
😯 2
😁 1