Created
September 8, 2019 13:28
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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