3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Kotlin Coroutinesで非同期並列処理をする

Last updated at Posted at 2019-05-12

非同期な処理を並列させて、それぞれが完了するまで待ち合わせます。onClick() を実行すると処理が始まります。

コード

並列処理の結果を使って処理を行います。

MainActivityViewModel.kt

class MainActivityViewModel : ViewModel(), LifecycleObserver {

    private val job = Job()
    private val scope = CoroutineScope(Dispatchers.Main + job)

    fun onClick() {
        scope.launch(Dispatchers.IO) {

            val t1 = async { task1() }
            val t2 = async { task2() }

            Timber.d("onComplete: %d", t1.await() + t2.await())
        }
    }

    private fun task1(): Int {
        Timber.d("task 1 START")
        Thread.sleep(2000)
        Timber.d("task 1 END")
        return 1
    }

    private fun task2(): Int {
        Timber.d("task 2 START")
        Thread.sleep(3000)
        Timber.d("task 2 END")
        return 2
    }

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

実行結果

task 1 START
task 2 START
task 1 END
task 2 END
onComplete: 3

RxKotlin版もありますので参考にしてください。状況に応じてRxとcoroutinesを使い分けると良いでしょう。
RxKotlinで非同期並列処理をする - Qiita

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?