3

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
  • You would need to define all external classes in Kotlin. So you would have generated external classes for each type you want to use from specific npm module. Have you tried using Dukat to generate external classes for that specific npm module? Commented Mar 29, 2022 at 4:17

1 Answer 1

0

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"))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.