Search code examples
androidkotlinkotlin-interopkotlinx.coroutines

How to easily consume a Kotlin channel producer in Java?


As part of working on the development of a new API, I am learning to use Kotlin. Initially I want the Kotlin API to be used within a Java (Android) project, but in the long term I hope to adopt Kotlin entirely.

As part of improving the implementation of a long-running process, I want to use coroutines. Specifically, a channel producer from the kotlinx.coroutines package.

For example:

fun exampleProducer() = produce {
    send("Hello")
    delay(1000)
    send("World")
}

What is the best way to consume this in Java? I am okay with adding temporary 'helper' functions to Kotlin and/or Java.


Solution

  • The easiest way to interop channels with Java is via Reactive Streams. Both Rx and Project Reactor are supported out-of-the-box. For example, add kotlinx-coroutines-rx2 to your dependicies and you'll be able to use rxFlowable builder:

    fun exampleFlowable() = rxFlowable<String> {
        send("Hello")
        delay(1000)
        send("World")
    }
    

    This function returns an instance of Flowable, which is specifically designed for ease-of-use from Java, for example, you can do in Java:

    exampleFlowable().subscribe(t -> System.out.print(t));