Skip to main content

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

note

This article has been translated by Gemini.

In this Notes article, I roughly jotted down notes in English from the content of the English session video/podcast. This article is intended to be read as a reference while watching the video. I hope this article helps you even a little when you watch the actual video. (Please feel free to contact me if there are any errors or typos!)

This article is based on 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

📝
#

  • Since LiveData is a data holder, objects you don’t want to keep in memory should not be passed.
  • If you need the concept of operators or streams, you should use libraries specialized in reactive concepts like RxJava.
  • Sharing LiveData instances should be avoided as much as possible (because LiveData in two Activities could become active at the same time). In such cases, generate a new LiveData each time. Generating LiveData is not that heavy a process.