Using coroutines what is the proper way to launch/...
# getting-started
i
Using coroutines what is the proper way to launch/execute multiple independent blocks in parallel? for example
Copy code
for taks in tasks:
launch { task }
or would it be something like:
Copy code
launch { task1, task2, ..., taskN }
1
d
The first launches N coroutines (which run in parallel*). The second launches one coroutine, which executes all the tasks in order. * (depending on the dispatcher they might not actually run in parallel)
i
ok cool, thank you! that’s what I thought from how I’d used them before - one more follow up question, if you had some networking tasks you wanted to run in parallel you could do (not correct syntax, but hopefully communicates the idea)
Copy code
Dispatchers.IO.launch { block.invoke() }
d
Yes, but the receiver for
launch
needs to be a
CoroutineScope
, not the dispatcher. To set the dispatcher you would use
launch(<http://Dispatchers.IO|Dispatchers.IO>) { }
👍 1
a
You only need to switch to an IO dispatcher if your networking operations are thread-blocking rather than suspending. Keep these concerns separate from other business logic if you can; let your lower level networking code worry about interop with blocking API calls and switch dispatchers if it has to while higher level code that coordinates different network operations thinks only in terms of suspending calls.
1
i
that makes sense, thank you! the case I’m looking at is with Bluetooth - which actually raises another lingering question I’ve had. What’re the appropriate dispatchers to use when working with Bluetooth?
d
Depends on the API. If it's a blocking API:
<http://Dispatchers.IO|Dispatchers.IO>
. If not, it depends™.
i
gotcha, thanks for the help!