検証環境
この記事の内容は、以下の環境で検証しました。
- Intellij IDEA ULTIMATE 2018.2
- Kotlin 1.3.0
- Gradle Projectで作成
- GradleファイルはKotlinで記述(KotlinでDSL)
準備
詳細は下記の準備を参照してください。
https://qiita.com/naoi/items/8abf2cddfc2cb3802daa
Making computation code cancellable
前回は、キャンセルの裏側の話をしました。
しかし、キャンセルできない処理についても話しました。今回のタイトルはそれをひっくり返すような感じがしますね。
早速読み進めます。
There are two approaches to making computation code cancellable. The first one is to periodically invoke a suspending function that checks for cancellation. There is a yield function that is a good choice for that purpose. The other one is to explicitly check the cancellation status. Let us try the later approach.
Replace while (i < 5) in the previous example with while (isActive) and rerun it.
意訳込みですが(略)
計算処理にキャンセル処理を実装する方法は2種類あります。1つ目は、suspend関数を定期的に呼び出し、キャンセル状態を確認する方法です。その場合は、yeil関数を呼び出すとよいでしょう。
2つ目の方法は、キャンセル状態を明示的ににチェックする方法です。isActiveを呼び出すことによりキャンセルされているか確認できます。
while(i<5)をwhile(isActive)に置き換えてみました。