【问题标题】:How to run multiple kotlin couroutines in parallel android?如何在并行android中运行多个kotlin协程?
【发布时间】:2021-02-23 06:23:36
【问题描述】:

我正在从 Android 设备中获取图像、视频和音乐文件。我想在不阻塞 UI 线程的情况下使用三个并行程序在后台运行我的代码。

suspend fun getImages() : ArrayList<VideoData> {
    
}
suspend fun getVideos() : ArrayList<ImageData> {

}
suspend fun getAudio() : ArrayList<AudioData> {

}

这三个函数必须并行执行。我不想等待所有这些都完成。当一个功能完成后,我想在主线程(即 UI 线程)上执行一些代码。

【问题讨论】:

标签: android kotlin background-process kotlin-coroutines


【解决方案1】:

使用协程是一种选择。

创建你的挂起函数:

suspend fun getImages() : ArrayList<VideoData> {

    withContext(Dispatchers.IO) {
        // Dispatchers.IO
        /* perform blocking network IO here */
    }
}
suspend fun getVideos() : ArrayList<ImageData> {...}
suspend fun getAudio()  : ArrayList<AudioData> {...}

创建工作

val coroutineJob_1 = Job()

创建范围

val coroutineScope_1 = CoroutineScope(coroutineJob + Dispatchers.Main)
       

在您的 Activity/Fragment 中启动具有范围的作业...

coroutineScope_1.launch {

     // Await
     val response = getImages()

     show(response)
}

show() 有你的 UI 代码。

您可以启动多个作业以并行工作...

coroutineScope_2.launch {...}
coroutineScope_3.launch {...}

【讨论】:

  • medium.com/androiddevelopers/… 看看这个关于使用协程的更多细节......
  • 我想并行执行它们。启动与异步?异步在哪里使用?
  • 你可以启动多个 Job 来并行工作... coroutineScope_2.launch {...} coroutineScope_3.launch {...}
  • stackoverflow.com/a/46226519/6269691 看看这个启动与异步的区别,基本上在启动时,你会在里面做所有的工作,而不是等待任何结果。对于异步,您会得到结果,然后在您调用它的地方执行...
猜你喜欢
  • 2019-12-18
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
  • 2020-10-07
  • 1970-01-01
  • 2021-12-08
相关资源
最近更新 更多