LoginSignup
2
1

More than 5 years have passed since last update.

Kotlin 1.3のCoroutineのキャンセル④(finally句でリソースを閉じる)

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

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

タイトルをみると、わからなくもないです。
キャンセルしたときにfinally句でリソースクローズする話だろうなとイメージはわきます。

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

Cancellable suspending functions throw CancellationException on cancellation which can be handled in a usual way.
For example, try {...} finally {...} expression and Kotlin use function execute their finalization actions normally when coroutine is cancelled:

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

キャンセル可能なSuspend(以降、サスペンド)関数は、キャンセルすると CancellationException 例外が発生します。
例えばtry-finnalyで囲い、キャンセル時に何かしらの終了処理をするには以下のように記述します。

なるほど、確かにキャンセル処理でfinally句が利用できれば、便利ですね。
サンプルコードをみてみます。

import kotlinx.coroutines.*

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

実行結果は以下のようになります。

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

たしかにキャンセルされたときにfinnaly句が実行されています。
このブロック最後の説明文にも以下のように記載されています。

Both join and cancelAndJoin wait for all the finalization actions to complete, so the example above produces the following output:

訳すと

joinとcancelAndJoinは、終了処理(finally句)が完了するまで、処理を待ちます。
結果として、上記のような結果になります。

まとめ

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

  • キャンセル可能なサスペンド関数はtry-finallyで終了処理を実装できる
2
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
2
1