hi, ``` suspend fun ServerSocket.listening() = sus...
# coroutines
h
hi,
Copy code
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
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
accept
in a
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
block) to prevent from blocking the main thread
h
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
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
Just wrapping to withContext will not help, you again just wrapping one blocked thread that cannot dispatch cancellation
h
thanks