LoginSignup
11
12

More than 5 years have passed since last update.

MediatorLiveDataとカスタムTransformation

Posted at

LiveDataのサブクラスにMediatorLiveDataというものがあります。
MediatorLiveDataは別のLiveDataを監視して自身の値を変更するLiveDataです。
公式のサンプルリポジトリに幾つかの用例を見ることができます。

TransformationsはLiveDataの値の変形や別のLiveDataに変換することができるクラスです。Transformationsはその実装にMediatorLiveDataを使用していて、独自のトランスフォーメーションを作成したい場合、同じようにMediatorLiveDataを使って実装することができます。

Sample.kt
fun <T1, T2, S> combineLatest(source1: LiveData<T1>, source2: LiveData<T2>,
                              func: (T1?, T2?) -> S?): LiveData<S> {
    val result = MediatorLiveData<S>()
    result.addSource(source1, {
        result.value = func.invoke(source1.value, source2.value)
    })
    result.addSource(source2, {
        result.value = func.invoke(source1.value, source2.value)
    })
    return result
}
11
12
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
11
12