https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

Sachin Maharana

10/21/2020, 7:23 AM
I have seen examples of using GlobalScope.launch and runBlocking to create coroutines. How i can create coroutines without using the above two options? Using runBlocking as coroutine builder launches coroutines on a single thread, but i don't want to that. And GlobalScope launches in the root scope and has to be taken care of. What other options i have?
b

Big Chungus

10/21/2020, 7:27 AM
Start your program in suspend fun main (yes, main can be suspend) and then just use coroutineScope {...} in your suspend functions 🙂
b

bezrukov

10/21/2020, 7:27 AM
runBlocking(Dispatchers.Default)
and it is not single threaded anymore. Or you can do a context switch inside (
withContext(Dispatchers....)
)
runBlocking / somescope.launch is only an entrypoint to the coroutine context when you can call
suspend
funs. Then you can do whatever you want
s

streetsofboston

10/21/2020, 12:30 PM
Create your own CoroutineScope.... Eg.
val scope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
z

Zach Klippenstein (he/him) [MOD]

10/21/2020, 2:14 PM
☝️ creating your own scope is probably the most flexible, just remember to cancel it when you’re done
5 Views