简体   繁体   English

Android 的任务队列 - Kotlin

[英]Tasks Queue for Android - Kotlin

I want to add Tasks (or Runnable) in queue that I want to execute in series.我想在要连续执行的队列中添加任务(或可运行)。 New task comes in at run time, depending on conditions.新任务在运行时进入,具体取决于条件。 I also want to add a delay after each task before it starts the next one.我还想在每个任务之后添加一个延迟,然后再开始下一个任务。

For example: I am downloading a file, and user taps another file to download.例如:我正在下载一个文件,用户点击另一个文件进行下载。 Now I dont want it to start in parallel.现在我不希望它并行启动。 I want it to start only after first file is downloaded.我希望它仅在下载第一个文件后才启动。

What would be the best way to do it in Kotlin for Android?对于 Android,在 Kotlin 中最好的方法是什么?

The following does what you are asking for:以下是您所要求的:

fun main() {
    val delay = { millis:Long ->  Runnable { println("delay..."); Thread.sleep(millis) } }
    val r1 = Runnable { println("r1") }
    val r2 = Runnable { println("r2") }
    val r3 = Runnable { println("r3") }

    val queue: List<Runnable> = listOf(r1, delay(1_000), r2, delay(2_000), r3)
    
    thread {
        queue.forEach { it.run() }
    }

    // alternatively, if you have an ExecutorService:
    // 
    // executorService.execute { queue.forEach { it.run() } }
}

prints:印刷:

r1
delay...
r2
delay...
r3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM