heihei blog

Blog icon by Unsplash https://unsplash.com/@virussinside

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


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





  • In order to observe LiveData you need to provide lifecycle
  • LiveData is going to remove subscription on appropriate lifecycle event, for free


  • 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


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


  • 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の生成はそこまで重たい処理ではない。