https://kotlinlang.org logo
#coroutines
Title
# coroutines
h

halim

04/18/2019, 11:47 AM
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

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
accept
in a
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
block) to prevent from blocking the main thread
h

halim

04/18/2019, 2:01 PM
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
Just wrapping to withContext will not help, you again just wrapping one blocked thread that cannot dispatch cancellation
h

halim

04/21/2019, 8:51 AM
thanks
2 Views