What is the recommanded what to turn Javascript ca...
# coroutines
s
What is the recommanded what to turn Javascript callback based API like
EventSource
to a
Flow
that emits the data received by the
onmessage
callback ?
My original code is:
Copy code
window.onload = {
		EventSource("/message/stream").onmessage = {
			val message = JSON.parse<Message>(it.data as String)
			val li = document.createElement("li").apply {
				innerHTML = "Message: ${message.content} from user ${message.user}"
			}
			document.getElementById("messages")!!.appendChild(li)
		}
		Unit // Ugly workaround for <https://youtrack.jetbrains.com/issue/KT-22635>
	}
I would like to extract the
EventSource("/message/stream").onmessage
to something that provides a
Flow<String>
I will then use operators to turn it to
Message
and do whatever is needed with the DOM
I tried:
Copy code
fun EventSource.asFlow() = flow {
	onmessage = {
		emit(JSON.parse<Message>(it.data as String))
		Unit
	}
}
But it does not work since
onmessage
is not suspending
v
Currently, the only way is to use `callbackFlow`/`channelFlow` (one is alias to another, the only difference is your intention): https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/channel-flow.html https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/callback-flow.html But you have to manage backpressure somehow: drop messages when
channel.offer
returns
false
, use conflated or unlimited channel
In the future we will provide StateFlow/DataFlow that are similar to Rx subjects/Reactor processors
s
Make sense, thanks for your feedback.
It is maybe too early but providing extensions like
EventSource.asFlow()
out of the box would increase significantly Kotlin added value for frontend developement.
v
s
Thanks, I will make a complete feedback after my Devoxx deepdive
v
it would be very helpful
s
I am pretty amazed by 2 things: - The awesomeness of Coroutines 1.3 on frontend - The lack of up to date documentation and samples given all the changes on Gradle + multiplatform + Kotlin JS
So the potential is huge
But at some point IMO you will need to pause the features and just make documentation up to date, provide samples and make multiplatform Gradle config more approachable.
1
But great stuff, congrats to the team
Another similatr question for single value callback, I saw https://stackoverflow.com/questions/48552925/existing-3-function-callback-to-kotlin-coroutines/48562175#48562175 but when I try to use it for
window.onload
I get compile time errors:
Copy code
suspend fun Window.awaitLoad() = suspendCoroutine<Unit> { cont ->
	onload = {
		cont.resume(Unit)
	}
}
I get
Methods are absent in coroutines classes since 1.3
Oh I used the wrong one
It works with
import kotlin.coroutines.suspendCoroutine