https://kotlinlang.org logo
#getting-started
Title
# getting-started
i

ink

12/21/2020, 7:44 PM
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

diesieben07

12/21/2020, 7:46 PM
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

ink

12/21/2020, 7:48 PM
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

diesieben07

12/21/2020, 7:55 PM
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

Adam Powell

12/21/2020, 7:56 PM
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

ink

12/21/2020, 8:00 PM
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

diesieben07

12/21/2020, 8:01 PM
Depends on the API. If it's a blocking API:
<http://Dispatchers.IO|Dispatchers.IO>
. If not, it depends™.
i

ink

12/21/2020, 8:10 PM
gotcha, thanks for the help!
4 Views