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

camdenorrb

07/25/2021, 8:53 PM
Copy code
package me.camdenorrb.generaltesting.coroutines

import kotlinx.coroutines.*

object TestBreaking1 {

    @JvmStatic
    fun main(args: Array<String>) {

        runBlocking {
            launch(<http://Dispatchers.IO|Dispatchers.IO>) {
                delay(10000000)
            }
            println("Here1")
        }

        println("Here2")
    }

}
This doesn't print "Here2" until the delay is done, is this expected?
👌 6
@Adam Powell How would I go about making it not do that?
a

Adam Powell

07/25/2021, 9:00 PM
What do you want it to do instead, and why do you want that?
c

camdenorrb

07/25/2021, 9:01 PM
I want it to act like a lightweight thread and not block the main thread while doing long term tasks or database fetching
e

ephemient

07/25/2021, 9:02 PM
use a real dispatcher instead of
runBlocking
.
j

Justin

07/25/2021, 9:13 PM
runBlocking
allows you to bridge regular blocking code to suspending style functions and coroutines. It creates a new coroutine to do this. With coroutines, a coroutine cannot complete normally until all its children complete (either normally or by cancellation) Since
runBlocking
runs a blocking parent coroutine, then it makes sense and is expected that
Here2
will not be printed until
runBlocking
and its children complete
If you want coroutine work to continue even after
main
completes for some reason, I’d make sure that’s necessary to accomplish what you want. If it is necessary, you’d have to use an asynchronous coroutine bridge like creating your own
CoroutineScope
and calling
yourScope.launch
instead of using
runBlocking
, but you’ll want to make sure you do cleanup of the CoroutineScope you create just as you would without coroutines when managing new threads. I’ve never continued work after
main()
finished, so I’m not 100% sure it will work and/or what you need to be careful about
c

camdenorrb

07/26/2021, 9:34 AM
Alright, thank y'all :3
4 Views