Kotlin Parallel Coroutines

Is it permissible to save several copies of the task from separate coroutines. Let's say I want to run a couple of coroutines at the same time in which they are not connected and cannot happen in one coroutine, but I want them to run in parallel. On Android, I have to save an instance of the job so that I can cancel the job in the onDestroy method. It would be acceptable to keep each task separately in the list, or I would break some rule. I know that they have Subscriptions in RX, why there is no equivalent in Kotlin Kotlin?

val jobList = arrayListOf<Job>()

fun startJob1() {
    jobList.add(launch {
        //do some work
    })

fun startJob1() {
    jobList.add(launch {
        //do some other unrelated work
    })

override fun onDestroy() {
    super.onDestroy()
    cancelAllActiveJobs(jobList)
}

Does this type of architecture make sense for coroutines?

+4
source share
2 answers

manullay Job, , - Job hierarhy, , .

, -, :

val job = Job()

, , , :

fun startJob1() {
    launch(job) { // make it a child
        //do some work
    }
}

fun startJob1() {
    launch(job) { // make it a child
        //do some other unrelated work
    }
}

, , .

override fun onDestroy() {
    super.onDestroy()
    job.cancel()
}

, . , , .

: https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md#cancellation-via-explicit-job

+3

, . , 100k :

val jobs = List(100_000) { // launch a lot of coroutines and list their jobs
        launch {
            delay(1000L)
            print(".")
        }
    }
 jobs.forEach { it.join() } 

, , , : while (isActive).

, :

fun main(args: Array<String>) = runBlocking {
    val startTime = System.currentTimeMillis()
    val jobs = arrayListOf<Job>()
    jobs += launch {
        var nextPrintTime = startTime
        var i = 0
        while (isActive) { // check if still active
            if (System.currentTimeMillis() >= nextPrintTime) {
                println("Job1: Sleeping ${i++} ...")
                nextPrintTime += 500L
            }
        }
    }

    //another job
    jobs += launch {
        while (isActive) { // check if still active
            if (System.currentTimeMillis() >= 42) {
                println("Job2: Sleeping 42 ...")
                delay(500L)
            }
        }
    }
    delay(1300L) // delay a bit
    println("main: Cancelling the sleeping job!")
    jobs.forEach { it.cancelAndJoin() } // cancels the job and waits for its completion
}
+2

Source: https://habr.com/ru/post/1689082/


All Articles