Colton Idle
03/05/2024, 2:47 AMval receiveChannel = socket.openReadChannel()
val sendChannel = socket.openWriteChannel(autoFlush = true)
launch(<http://Dispatchers.IO|Dispatchers.IO>) {
while (true) {
println("awaiting readUtf8Line")
val greeting = receiveChannel.readUTF8Line()
if (greeting != null) {
println(greeting)
} else {
print("got a line that's null?")
}
}
}
its basically copied from https://ktor.io/docs/servers-raw-sockets.html#client-exampleShawn
03/05/2024, 3:15 AMTobias Suchalla
03/05/2024, 8:56 AMwhile(isActive)
to support cancellation.
https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/is-active.htmlCLOVIS
03/05/2024, 9:05 AMisActive
anyway, if only just to make it clear that the loop is being controlled from the outside.Joffrey
03/05/2024, 9:23 AMisActive
if you call suspend functions that support prompt cancellation. That's just extra noise to look at when reading the code IMOCLOVIS
03/05/2024, 9:55 AMif you call suspend functions that support prompt cancellationHow do I know if a suspend function supports prompt cancellation? I thought the act of calling a suspend function itself supports it
Joffrey
03/05/2024, 9:57 AMCancellationException
when calling it. Most suspend functions will throw though, so it should be fine to assume that it will work most of the time, unless you're calling a function with a suspend
keyword that isn't actually cancellable. E.g. a suspend function implemented with suspendCoroutine
instead of suspendCancellableCoroutine
, or a function marked with suspend
but that is just a normal blocking function.CLOVIS
03/05/2024, 9:58 AMJoffrey
03/05/2024, 10:14 AMJoffrey
03/05/2024, 10:17 AMJoffrey
03/05/2024, 10:17 AMisActive
IMO. Also, just checking for isActive
wouldn't propagate the cancellation exception (not sure if that has any bad consequence), so maybe a better way would be to use coroutineContext.ensureActive()
.