suspend fun ServerSocket.listening() = suspendCancellableCoroutine<Socket>{
it.invokeOnClancellation { println("coroutine is cancelling...."); close() }
it.resueWith(Result.success(accpet())
}
fun main() = runBlocking() {
withTimeout(3000) {
val socket = ServerSocket(4000).run { listening() }
}
}
i expected to cancel after 3 sec but not think happen, server still listening and wait for client to connect
why suspendCancellableCoroutine not cancelled ?? any idea
t
tseisel
04/18/2019, 12:32 PM
IO in Java, such as Sockets and InputStreams are blocking by nature. Wrapping blocking code with coroutines does not make it magically suspending ; you have to do the blocking stuff on another thread (for example, calling
thanks, even if use withContext(....) and try to cancel does not work !!! mots IO in java is blocking so in witch suspendCancellableCoroutne is usefull ??
g
gildor
04/18/2019, 4:27 PM
suspendCancellableCoroutine is useful of course, but not sure that it will work without wrapping to own coroutineScope where blocking and cancellation are dispatched on different threads
gildor
04/18/2019, 4:28 PM
Just wrapping to withContext will not help, you again just wrapping one blocked thread that cannot dispatch cancellation