Menu

Turn a callback WebSocket feed into a Kotlin Flow with callbackFlow (with a live feed to try it on)
📰

Turn a callback WebSocket feed into a Kotlin Flow with callbackFlow (with a live feed to try it on)

DEV Community: kotlin·Malek·2 days ago
#UDWI57hO
#devtokotlin#devto#dev#block#flow
Reading 0:00
15s threshold

Most APIs that push data hand you a callback. Kotlin code would rather have a Flow . callbackFlow is the bridge, and

it is short, but two details decide whether your version leaks sockets: where the cleanup goes, and whether the Flow is

cold.

To have something real to wrap, this article uses a public blockchain network that emits a block every 15 seconds over

a WebSocket. It needs no API key and no account, so the code runs as written. You do not need to know anything about

the chain; treat it as a server that pushes one event every 15 seconds.

The project

build.gradle.kts :

plugins { kotlin ( "jvm" ) version "2.2.0" application }

repositories { mavenCentral ( ) }

dependencies { implementation ( "org.janzeer:janzeer-sdk-client:0.1.7" ) implementation ( "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2" ) }

kotlin { jvmToolchain ( 17 ) } application { mainClass .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.