Skip to content

Instantly share code, notes, and snippets.

@SaurabhSandav
Created September 8, 2019 13:28
Show Gist options
  • Select an option

  • Save SaurabhSandav/5f3a90c531121857caf575da68bb47af to your computer and use it in GitHub Desktop.

Select an option

Save SaurabhSandav/5f3a90c531121857caf575da68bb47af to your computer and use it in GitHub Desktop.
Similar to MediatorLiveData but limited to a single LiveData source at a time.
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
class SwapSourceLiveData<T> : LiveData<T>() {
private var currentSource: LiveData<T>? = null
private var currentObserver: Observer<T>? = null
fun swapSource(newSource: LiveData<T>, newObserver: Observer<T> = Observer { value = it }) {
unPlug()
currentSource = newSource
currentObserver = newObserver
if (hasActiveObservers()) plug()
}
override fun onActive() {
super.onActive()
plug()
}
override fun onInactive() {
super.onInactive()
unPlug()
}
private fun plug() {
currentObserver?.let { currentSource?.observeForever(it) }
}
private fun unPlug() {
currentObserver?.let { currentSource?.removeObserver(it) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment