How to use AsyncGenerators with Kotlin/JS?

229 Views Asked by At

I'm currently trying to use IPFS with Kotlin/JS, though my problem isn't specific to that. The ipfs.cat() and ipfs.get() functions return an AsyncGenerator and I'm unsure how to iterate over it with Kotlin (I'm not even sure which type would best represent an AsyncIterable in kotlin)

The below code is an minimal version of what I'm trying to do, though I have not tested the code as is below. It fails with a ClassCastException since the for loop is fundamentally wrong, but I don't know what I should replace it with.

File1:

@file:JsModule("ipfs-core")
@file:JsNonModule

import kotlin.js.Promise

@JsName("create")
external fun create(config: Any = definedExternally): Promise<dynamic>

File2:

create().then { ipfs: dynamic ->
    ipfs.id().then { id: dynamic ->
        myId = id.id as String
        println(JSON.stringify(id))
    }
    val result: dynamic = ipfs.cat("bafkreihapp6racx2xf5gwnrgtsr56r37kazui3jvzzmot2nx2t6h6g2oom")
    // result is an AsyncGenerator

    // below fails with ClassCastException
    for (element: dynamic in result){
        println(element)
    }
}
1

There are 1 best solutions below

0
On

This was the solution I came up with: I needed to move everything into an async context and then I iterated manually over the AsyncGenerator:

                   val result: dynamic = ipfs.cat("bafkreihapp6racx2xf5gwnrgtsr56r37kazui3jvzzmot2nx2t6h6g2oom")
                   val resultArray = js("[]")
                   var cont: Boolean = true

                       while (cont) {
                           result.next().then { currentNext: dynamic ->
                               val value: dynamic = currentNext.value
                               val done: Boolean = currentNext.done
                               if (done) {
                                   println("done")
                                   cont = false
                               } else {
                                   println("got: ${currentNext.value}")
                                   resultArray.push(currentNext.value)
                               }
                           }
                       }
                       println(resultArray.joinToString("\n"))