Edoardo Luppi
06/20/2023, 9:03 AMactual fun connect(host: String, port: Int, listener: Result<ServerProperties>) {
GlobalScope.launch {
connectAsync(port, host).await() // Await a JS promise
val length = readUnsignedIntAsync().await() // Await a JS promise
val data = readStringAsync(length).await() // Await a JS promise
val serverProperties = ServerProperties(data)
listener.onSuccess(serverProperties)
}
}
Would the above code be considered "ok"?turansky
06/20/2023, 1:01 PMconnectAsync - custom function?Edoardo Luppi
06/20/2023, 1:02 PMPromise, that I coded myself in Kotlinturansky
06/20/2023, 1:02 PMsuspend fun?Edoardo Luppi
06/20/2023, 1:03 PMprivate fun connectAsync(port: Int, host: String): Promise<Any?> =
Promise { resolve, reject ->
val errorHandler: (Error) -> Unit = {
socket.removeAllListeners(Event.CONNECT)
reject(it)
}
val connectHandler = {
socket.removeListener(Event.ERROR, errorHandler)
resolve(null)
}
socket.once(Event.ERROR, errorHandler)
socket.setKeepAlive(true)
socket.setTimeout(1000)
socket.connect(port, host, connectHandler)
}Edoardo Luppi
06/20/2023, 1:04 PMturansky
06/20/2023, 1:07 PMturansky
06/20/2023, 1:07 PMturansky
06/20/2023, 1:07 PMEdoardo Luppi
06/20/2023, 1:18 PMEdoardo Luppi
06/20/2023, 3:12 PMsuspendCancellableCoroutine is an option? So I don't have to use the JS promiseEdoardo Luppi
06/20/2023, 3:29 PMconnectAsync. This avoids using await, and propagating the same concept to writing and reading bytes avoids the Promise's then usages
private suspend fun connectAsync(port: Int, host: String) {
suspendCancellableCoroutine { continuation ->
val errorHandler: (Error) -> Unit = {
socket.removeAllListeners(Event.CONNECT)
continuation.resumeWithException(it)
}
val connectHandler = {
socket.removeListener(Event.ERROR, errorHandler)
continuation.resume(Unit)
}
socket.once(Event.ERROR, errorHandler)
socket.setKeepAlive(true)
socket.setTimeout(1000)
socket.connect(port, host, connectHandler)
}
}Edoardo Luppi
06/20/2023, 3:30 PMEdoardo Luppi
06/20/2023, 6:18 PMEventEmitter.once(socket, Event.ERROR)Edoardo Luppi
06/20/2023, 6:21 PMturansky
06/20/2023, 7:48 PMturansky
06/20/2023, 7:48 PMon and once on the same level with EventEmitter (not checked)turansky
06/20/2023, 8:01 PM