Android Architecture Blueprints での コルーチンの使われ方

良い記事がたくさんあります。

Kotlin の Coroutine を概観する

入門Kotlin coroutines

読んでみましたが、きちんと理解できてる自信がありません!

MVPの中で、どのように使われているかAndroid Architecture Blueprintsで見てみましょう。

todo-mvp-kotlin-coroutines

すべての非同期処理をコルーチンで置き換えます。シンプルな非同期プログラミングとなり、直感的にコード書くことができます。

 

Presenter

非同期処置の記述はここが起点になります。


private fun loadTasks(forceUpdate: Boolean, showLoadingUI: Boolean) = launchSilent(uiContext) {
    // ...
    val result = tasksRepository.getTasks()
    // ...
}

TasksPresenter.kt#L69

メインのデータをリポジトリから取得する部分です。


launchSilent(uiContext) {
  // ...
}

CoroutineExt.kt#L18-L25

と見慣れない コルーチンビルダーがありますが、元の形に戻すと、


launch(
  context = UI,
  start = CoroutineStart.DEFAULT,
  parent = null) {
  // ...
}

AppExecutors.kt#L32-L35

です。

Presenterでは、launch() でコルーチンの起点を作っています。

Viewのメソッドを利用しないメソッドでは、コルーチンコンテクストは、DefaultDispatcher となり省略することができます。

 

Repository


override suspend fun getTasks(): Result<List<Task>> {
  // ...
  val result = tasksLocalDataSource.getTasks()
  // ...
 }

TasksRepository.kt#L49-L69


override suspend fun getTasks(): Result<List<Task>> = withContext(appExecutors.ioContext) {
  // ...
  Result.Success(tasksDao.getTasks())
  // ...
}

TasksLocalDataSource.kt#L34-L41

Repository -> LocalDataSource とサスベンドなfunctionが深く呼ばれていきます。

LocalDataSource では、Presenterでのlauch()時のコルーチンコンテキストから、withContext(appExecutors.ioContext) として、すべて、ioContext としての DefaultDispatcher に一時的に切り替えています。

 

まとめ

ざっくり、コルーチン関連の入れ子関係を書いてみると、


// presenter
launch(context = UI, parent = null) {

  // repository
  withContext(DefaultDispatcher) {
    // fetch data from database
  }

}

Presenter で launch() して、Repository末端(local/remote) で withContext() でコンテクスト切り替え。

もちろん、コルーチン内から呼ばれるのは、repository の suspend な functionず。


SharedPreferences で putStringSet() が1つしか保存できない。

何ですか、この動きは。

「Preference から Set を取得後、追加して再保存する」

問題なく以下のようなテストも通過します。


@Test fun getStringSet() {

  val key = "key"
  val preferences = context.getSharedPreferences(key, Context.MODE_PRIVATE)
  val beforeData = preferences.getStringSet(key, mutableSetOf())
  val beforeSize = beforeData.size

  beforeData.add(System.currentTimeMillis().toString())
  preferences.edit()
      .putStringSet(key, beforeData)
      .commit()

  val afterData = preferences.getStringSet(key, mutableSetOf())
  val afterSize = afterData.size

  println("$beforeData -> $afterData")
  println("$beforeSize -> $afterSize")
  assertEquals(beforeSize + 1, afterSize)

}


I/System.out: [1520865219872, 1520865358333] -> [1520865219872, 1520865358333]
I/System.out: 1 -> 2

しかし、何回実行してもデータが1つのままで増えていきません。


I/System.out: [1520865219872, 1520865504185] -> [1520865219872, 1520865504185]
I/System.out: 1 -> 2

I/System.out: [1520865219872, 1520865553254] -> [1520865219872, 1520865553254]
I/System.out: 1 -> 2

実際にファイルを確認してみると、


mako:/data/data/com.example.cryptocurrency/shared_prefs # cat key.xml
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <set name="key">
        <string>1520865219872</string>
    </set>
</map>

1つしか保存されてないですね!

クソですね!

なぜなのか?

android - Misbehavior when trying to store a string set using SharedPreferences - Stack Overflow

Android compares the modified HashSet that you are trying to save using SharedPreferences.Editor.putStringSet with the current one stored on the SharedPreference, and both are the same object!!!

A possible solution is to make a copy of the Set returned by the SharedPreferences object

どうやら、同じオブジェクトの比較となるので保存してくれないようです。

読み出し後、すぐコピーすればいいのですね!


val beforeData = preferences.getStringSet(key, mutableSetOf()).toMutableSet()

なんとなく、よくある話のような気がします。


【Kotlin】coroutine 複数の非同期処理をまとめてキャンセルする

非同期処理には必ず絡んでくるのがライフサイクル。

RxJava のようにまとめたいですよね。


private CompositeDisposable compositeDisposable =
    new CompositeDisposable();

@Override public void onCreate() {
  compositeDisposable.add(backendApi.loadUser()
      .subscribe(this::displayUser, this::handleError));
}

@Override public void onDestroy() {
  compositeDisposable.clear();
}

SendChannel を使って同様にこのような。


interface JobHolder {
  val job: Job
}


class MainActivity : AppCompatActivity(), JobHolder {

  override val job: Job = Job()

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    addJob {
      while (true) {
        delay(500)
        println("A")
      }
    }

    addJob {
      while (true) {
        delay(1000)
        println("B")
      }
    }

  }

  // Job の actor として action を登録する
  private fun addJob(action: suspend () -> Unit) {

    val actor = actor<Unit>(job + UI, capacity = Channel.CONFLATED) {
      for (event in channel) action()
    }
    actor.offer(Unit)
  }


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

}

まとめてキャンセルできましたね!

どうせなら作って置いたらどうだろう。


class JobHolder {

  private val job = Job()

  fun add(action: suspend () -> Unit) {
    val actor = actor<Unit>(job + UI, capacity = Channel.CONFLATED) {
      for (event in channel) action()
    }
    actor.offer(Unit)
  }

  fun cancel() {
    job.cancel()
  }
}

Lifecycle and coroutine parent-child hierarchy
Children of a coroutine

 

こうでもいけるってよ: 2018-04-27追記


val rootParent = Job()

fun foo() {
  launch(UI, parent = rootParent) {
    // ...
  }
}

fun bar() {
  launch(CommonPool, parent = rootParent) {
    // ...
  }
}

fun destroy() { rootParent.cancel() }

Kotlin Coroutines on Android: Things I Wish I Knew at the Beginning