メインコンテンツへスキップ

Notes - Fun with LiveData (Android Dev Summit '18)

※Notes記事では、英語のセッション動画やポッドキャストの内容を(雑に)英語でメモに書き残すことを行っています。本記事は、あくまで動画を見ながら、参考程度に読んでいただくことを想定しています。Notes記事には雑メモ程度のものだったり、書き起こしのようなものもあります。これから実際の動画を見る際には、本記事の内容が少しでもお役に立てば幸いです。(内容において不備、誤字脱字等ありましたら気軽にご連絡いただけると嬉しいです。)

本記事は、Fun with LiveData (Android Dev Summit ‘18)の記事です。

f🆔shaunkawano:20181216213849p:plain

LiveData
#

Simple
#

Lifecycle-aware
#

  • In order to observe LiveData you need to provide lifecycle

  • LiveData is going to remove subscription on appropriate lifecycle event, for free

Observable
#

  • Activity and other view components have different lifecycle

  • Even Activity, when rotation changed, gets recreated and if some components have a reference to this activity then it leads to memory leak or worst, crash with NPE

=> Instead of letting something have reference of Activity, letting Activity observe live data is safe.

Data Holder
#

  • Live data is not a stream, data holder

  • If you want some stream concept use Rx

Transformations
#

  • If you use LiveData and ViewModel, you totally need to have transformations

Antipatterns
#

  • Storing big objects across Transformations

  • Sharing instances of LiveData

class SharedLiveDataRepository(val dataSource: MyDataSource) {
  private val result = MutableLiveData<Long>()

  fun loadItem(itemId: String): LiveData<Long> {
    result.value = dataSource.getData(itemId)
    return result // here we share the `result` LiveData
  }
}
  • Edge case: Activity Transitions

    • Two activities are active at the same time

    • If your class is a repository and you are creating a field of LiveData then maybe you are doing something wrong

When NOT to use LiveData
#

  • If you need a lot of operators or streams, use Rx.

  • If your operations are not about UI or lifecycle, use callback interfaces

  • If you have one-shot operation chaining, use coroutines

📝
#

  • LiveDataはデータホルダーなのでメモリに保持したくないようなオブジェクトは渡すべきではない

  • オペレーターやストリームの概念が必要なのであればRxJavaなどのリアクティブのコンセプトに特化したライブラリを使うべき

  • LiveDataのインスタンス共有は、(2つのAcitvity内のLiveDataが同時にActiveになる可能性があるため)極力避ける。そのような場合は都度、新しいLiveDataを生成。LiveDataの生成はそこまで重たい処理ではない。