I have seen examples of using GlobalScope.launch a...
# coroutines
s
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
Start your program in suspend fun main (yes, main can be suspend) and then just use coroutineScope {...} in your suspend functions 🙂
b
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
Create your own CoroutineScope.... Eg.
val scope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
z
☝️ creating your own scope is probably the most flexible, just remember to cancel it when you’re done