https://kotlinlang.org logo
#android
Title
# android
v

vapoyan

06/18/2021, 2:08 PM
Hey I have following problem
Copy code
private 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 ?
c

CLOVIS

06/19/2021, 9:38 AM
If you are using a blocking library, there is no way to make it non-blocking. The idea is to have that blocking library work somewhere ‘safe', so it looks like it's suspending for the rest of the code. You do that by dispatching it to
<http://Dispatchers.IO|Dispatchers.IO>
, a thread pool that exists specifically for blocking stuff. Your code would look like:
Copy code
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.kt
👍 1
👏 1
You can think of
Copy code
withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
  foo()
}
as something similar to
Copy code
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)