LoginSignup
4
1

More than 5 years have passed since last update.

Kotlin 1.3のCoroutineのキャンセル①(コルーチンをキャンセルする)

Posted at

検証環境

この記事の内容は、以下の環境で検証しました。

  • Intellij IDEA ULTIMATE 2018.2
  • Kotlin 1.3.0
  • Gradle Projectで作成
  • GradleファイルはKotlinで記述(KotlinでDSL)

準備

詳細は下記の準備を参照してください。
https://qiita.com/naoi/items/8abf2cddfc2cb3802daa

Cancelling coroutine execution

前回に引き続き、公式サイトを読み解いていきます。

これまでの記事でキャンセルも少しだけふれましたが、今回からはキャンセルの詳細について説明していきます。

それでは、読み進めます。

In a long-running application you might need fine-grained control on your background coroutines.
For example, a user might have closed the page that launched a coroutine and now its result is no longer needed and its operation can be cancelled.
The launch function returns a Job that can be used to cancel running coroutine:

意訳込みですが、訳すと以下のとおりです。

長時間アプリを実行していると、バックグラウンドで実行しているコルーチンを制御する必要がでてきます。
例えば、ユーザが対象のページを閉じてしまった場合、コルーチンは結果を返す必要がなくなります。そして、そのような場合、キャンセルできます。
コルーチンを起動する関数は、コルーチンをキャンセルできるJobを返します。

そうでしたね。確かJobオブジェクトが取得できるんでした。

サンプルコードを確認してみましょう。

import kotlinx.coroutines.*

fun main() = runBlocking {
    //sampleStart
    val job = launch {
        repeat(1000) { i ->
            println("I'm sleeping $i ...")
            delay(500L)
        }
    }
    delay(1300L) // delay a bit
    println("main: I'm tired of waiting!")
    job.cancel() // cancels the job
    job.join() // waits for job's completion
    println("main: Now I can quit.")
    //sampleEnd
}

launch関数の戻り値でジョブを取得してますね。
その後、cancel関数を呼び出してキャンセルしています。
実行してみるとこんな結果になります。

I'm sleeping 0 ...
I'm sleeping 1 ...
I'm sleeping 2 ...
main: I'm tired of waiting!
main: Now I can quit.

しっかりキャンセルされていることが確認できます。

更に読み進めると。。。

As soon as main invokes job.cancel, we don't see any output from the other coroutine because it was cancelled.
There is also a Job extension function cancelAndJoin that combines cancel and join invocations.

訳してみると

mainがcancel関数を呼びだすと出力がキャンセルされます。
JobにはcancelAndJoinという関数が存在します。cancelとjoinを組み合わせた動作をします。

まとめ

このブロックで理解できたことは以下のことだと思います。

  • Jobのcancel関数を呼び出すとコルーチンが中断する
  • cancelAndJoin関数が存在すること
4
1
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
4
1