【MVVM】Transformations.switchMap() の使い方

👉 ViewModels and LiveData: Patterns + AntiPatterns – Android Developers – Medium 
👉 LiveData beyond the ViewModel — Reactive patterns using Transformations and MediatorLiveData 

LiveData をリアクティブに操作できるこのユーティリティメソッド。

LiveData を変換します。
これから返されるLiveData オブジェクトを Observe しておけば、Observer のライフサイクルを考慮しながら、データを変換することができます。lazy に処理され、呼び出しや依存関係の記述なしに、ライフサイクル関連の動作が引き継がれます。

👉 Transformations | android.arch.lifecycle.Transformations  |  Android Developers 

実体は MediatorLiveData のユーティリティ

ソースコードを見てみます。


@SuppressWarnings("WeakerAccess")
public class Transformations {

    private Transformations() {
    }

    @MainThread
    public static <X, Y> LiveData<Y> map(
            @NonNull LiveData<X> source,
            @NonNull final Function<X, Y> mapFunction) {
        final MediatorLiveData<Y> result = new MediatorLiveData<>();
        result.addSource(source, new Observer<X>() {
            @Override
            public void onChanged(@Nullable X x) {
                result.setValue(mapFunction.apply(x));
            }
        });
        return result;
    }

    @MainThread
    public static <X, Y> LiveData<Y> switchMap(
            @NonNull LiveData<X> source,
            @NonNull final Function<X, LiveData<Y>> switchMapFunction) {
        final MediatorLiveData<Y> result = new MediatorLiveData<>();
        result.addSource(source, new Observer<X>() {
            LiveData<Y> mSource;

            @Override
            public void onChanged(@Nullable X x) {
                LiveData<Y> newLiveData = switchMapFunction.apply(x);
                if (mSource == newLiveData) {
                    return;
                }
                if (mSource != null) {
                    result.removeSource(mSource);
                }
                mSource = newLiveData;
                if (mSource != null) {
                    result.addSource(mSource, new Observer<Y>() {
                        @Override
                        public void onChanged(@Nullable Y y) {
                            result.setValue(y);
                        }
                    });
                }
            }
        });
        return result;
    }
}

👉 Cross Reference: Transformations.java 

ソースコードより、これは、1:1 の MediatorLiveData を使うための便利ツールです。


class MainViewModel {
  val repositoryResult = Transformations.switchMap(userManager.user) { user →
     repository.getDataForUser(user)
  }
}

複数に変換したい場合は、直接 MediatorLiveData を使うのが良いでしょう。


val liveData1: LiveData<Int> = ...
val liveData2: LiveData<Int> = ...

val result = MediatorLiveData<Int>()

result.addSource(liveData1) { value →
    result.setValue(value)
}
result.addSource(liveData2) { value →
    result.setValue(value)
}

まとめ

ViewModel 内で、その下にある Repository との間で使います。

View (Activity / Fragment) のライフサイクルにも考慮されています。

ViewModel内で、データの id からその詳細情報の取得をしたり、検索文字列をフィルターとしてデータ抽出したり、などに使うことが多いようです。

👉 MediatorLiveDataとTransformationsでViewModelを効果的に使う 


AbsentLiveData とは?

あちこちで見かける AbsentLiveData。

ViewModel の中で以下のように使われています。


val game: LiveData<RefreshableResource<GameEntity>> = Transformations.switchMap(_gameId) { gameId ->
    when (gameId) {
        BggContract.INVALID_ID -> AbsentLiveData.create()
        else -> gameRepository.getGame(gameId)
    }
}

調べてみると、

どうやら、null の入った LiveData のようです。


/**
 * A LiveData class that has `null` value.
 */
class AbsentLiveData<T : Any?> private constructor(): LiveData<T>() {
    init {
        // use post instead of set since this can be created on any thread
        postValue(null)
    }

    companion object {
        fun <T> create(): LiveData<T> {
            return AbsentLiveData()
        }
    }
}

👉 android-architecture-components/AbsentLiveData.kt at master · googlesamples/android-architecture-components 

うん、揃う。

これは、コピペで使っていきましょう。


簡単に Play Store の説明画像が作成できる「Android App Mockup (Beta)」

このサイト。

👉 App Mockup Builder for App Store & Play Store | AppMockUp 

ブラウザ上でPlayStoreにアップロードするための画像が簡単に作成できます。

まずテンプレートを選んで、

スクリーンショットをアップロードして、テキストやカラーなどを設定していきます。

すぐにそれらしくできちゃいます!!

便利なツールです。


【公式 2018-05-07】Android Pie のバージョンシェア がひそかに 10%超えている件

前回の2018年10月からひさびさの更新となります公式 Android Developers のこのページ。

Android Pie の割合が10%を超えたようです。

しかし、更新日付が以前のままです。

ダッシュボード  |  Android Developers

英語版を見てみます。

Distribution dashboard  |  Android Developers

「日本語版の更新日付部分」のみが古いまま。

このページに関しては、どうやら英語版のページを確認したほうがよさそうです。



【Kotlin】バッキング・フィールド/プロパティ

フィールド

Fields cannot be declared directly in Kotlin classes.
Kotlin クラスでは、直接にフィールドを宣言することはできません。

プロパティ


// Kotlin
class Human {
    val age = 20
}


// Java
public final class Human {
   private final int age = 20;

   public final int getAge() {
      return this.age;
   }
}

バッキング・フィールド

ゲッターやセッターにカスタムロジックを入れたい場合は、「バッキング・フィールド」を使うことができます。

カスタムゲッターやセッターのスコープ内で「field」にアクセスできます。


// Kotlin
var counter = 0
    set(value) {
        if (value >= 0) field = value
    }


// Kotlin
class Human {
    val age = 20
        get() {
            println("Age is: $field")
            return field
        }
}


// Java
public final class Human {
   private final int age = 20;

   public final int getAge() {
      String var1 = "Age is: " + this.age;
      System.out.println(var1);
      return this.age;
   }
}

バッキング・プロパティ

ゲッターやセッターの外でフィールドに直接アクセスしたいときなどに使います。

private なフィールドに_を付けて明示します。


// Kotlin
private var _table: Map<String, Int>? = null
public val table: Map<String, Int>
    get() {
        if (_table == null) {
            _table = HashMap() // Type parameters are inferred
        }
        return _table ?: throw AssertionError("Set to null by another thread")
    }


// Kotlin
class Human {
    private val _age: Int = 20
    val age: Int
        get() {
            return _age
        }

     val printAge = {
         println("Age is: $_age")
     }
}


// Java
public final class Human {
   private final int _age = 20;
   @NotNull
   private final Function0 printAge = (Function0)(new Function0() {
      public Object invoke() {
         this.invoke();
         return Unit.INSTANCE;
      }

      public final void invoke() {
         String var1 = "Age is: " + Human.this._age;
         System.out.println(var1);
      }
   });

   public final int getAge() {
      return this._age;
   }

   @NotNull
   public final Function0 getPrintAge() {
      return this.printAge;
   }
}

まとめ

Java にデコンパイルした状況を確認しながら進むと理解しやすいように思います。

👉【Kotlin】Properties and Fields: Getters, Setters
👉 Properties and Fields: Getters, Setters, const, lateinit - Kotlin Programming Language
👉 Backing properties in Kotlin – ProAndroidDev
👉【MVVM】 ViewModel の_プロパティ記述