vapoyan
06/18/2021, 2:08 PMprivate var socket: DatagramSocket = ....
fun startListening() {
while (socket != null) {
socket?.receive(packet) // we are blocked here untill we receive packet
}
}
How I can implement this with coroutines, so it's running async and not blocking ?CLOVIS
06/19/2021, 9:38 AM<http://Dispatchers.IO|Dispatchers.IO>
, a thread pool that exists specifically for blocking stuff.
Your code would look like:
suspend fun startListening() {
while (socket != null) {
withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
socket?.receive(packet)
}
}
}
Here's a full example: https://gitlab.com/clovis-ai/reseau-s8/-/blob/master/client/src/main/kotlin/fr.ipb.reseau/Client.ktCLOVIS
06/19/2021, 9:42 AMwithContext(<http://Dispatchers.IO|Dispatchers.IO>) {
foo()
}
as something similar to
somewhereSafe.async {
foo()
}.await()
The current coroutine suspends without blocking the current thread, another thread starts to work and gets blocked, when it is done the previous coroutine gets the result.
(Note though that this message is just about what it looks like, withContext has much better optimizations and stuff for structured concurrency)