https://kotlinlang.org logo
#ktor
Title
# ktor
d

Dazai

09/22/2021, 4:45 PM
hey guys I was hoping to get some feedback on whether i'm using coroutines & ktor sockets properly. It feels weird to be writing a bunch of CoroutineScope(Dispatchers.IO).launch { while(true){ ... do stuff}}} everywhere https://gist.github.com/abueide/f086f6e0cc00c5bd8daf793cc66e0b96
a

ade

09/22/2021, 5:47 PM
I don't think you should create scopes like that. That would basically be equivalent to using GlobalScope which is not recommended usually.
d

Dazai

09/22/2021, 6:44 PM
what would the proper way to do it be?
a

Aleksei Tirman [JB]

09/22/2021, 7:12 PM
Since the coroutine context is inherited you don't need to specify a dispatcher every time you run child coroutine. I think it's OK to have
while(true)
loops in your case because you need to process clients and read data from them indefinitely. Have a look at the example in the documentation.
d

Dazai

09/22/2021, 7:14 PM
ah okay, thank you. I was confused I thought that if i didn't launch them in separate coroutines they would block eachother
a

Aleksei Tirman [JB]

09/22/2021, 7:16 PM
You need to call
launch
for each of them but don't have to specify
<http://Dispatchers.IO|Dispatchers.IO>
if the parent coroutine already has that dispatcher.
3 Views