如何在android中并行运行多个kotlin例程?
我正在从android设备获取图像、视频和音乐文件。我希望在后台使用三个并行例程运行代码,而不阻塞UI线程如何在android中并行运行多个kotlin例程?,android,kotlin,background-process,kotlin-coroutines,Android,Kotlin,Background Process,Kotlin Coroutines,我正在从android设备获取图像、视频和音乐文件。我希望在后台使用三个并行例程运行代码,而不阻塞UI线程 suspend fun getImages() : ArrayList<VideoData> { } suspend fun getVideos() : ArrayList<ImageData> { } suspend fun getAudio() : ArrayList<AudioData> { } suspend fun getIma
suspend fun getImages() : ArrayList<VideoData> {
}
suspend fun getVideos() : ArrayList<ImageData> {
}
suspend fun getAudio() : ArrayList<AudioData> {
}
suspend fun getImages():ArrayList{
}
挂起有趣的getVideos():ArrayList{
}
suspend fun getAudio():ArrayList{
}
这三个功能必须并行执行。我不想等待它们全部完成。当一个函数完成时,我想在主线程(即UI线程)上执行一些代码。使用协程是一个选项
suspend fun getImages() : ArrayList<VideoData> {
}
suspend fun getVideos() : ArrayList<ImageData> {
}
suspend fun getAudio() : ArrayList<AudioData> {
}
创建挂起函数:
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 coroutineScope_1 = CoroutineScope(coroutineJob + Dispatchers.Main)
在活动/片段中启动具有范围的作业
coroutineScope_1.launch {
// Await
val response = getImages()
show(response)
}
show()
有您的UI代码
您可以启动多个作业以并行工作
coroutineScope_2.launch {...}
coroutineScope_3.launch {...}
基本上不一样吗?看看这个,了解关于使用协同程序的更多细节……我想并行执行它们。启动vs异步?异步的用途在哪里?您可以启动多个作业来并行工作。。。coroutineScope_2.launch{…}coroutineScope_3.launch{…}看看这两个函数在launch和async之间的区别,基本上在launch中,您将在内部完成所有工作,而不是等待任何结果。对于async,您得到结果,然后在调用它的位置执行。。。