Created
March 2, 2020 10:21
-
-
Save fluxtah/87b149238cd2edc9d56e6edbf2f342b6 to your computer and use it in GitHub Desktop.
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
@Composable | |
fun <T> observe(@Pivotal data: LiveData<T>, block: ObserveScope<T>.() -> Unit) { | |
onActive { | |
val context = ObserveScope<T>() | |
block(context) | |
context.onStartBlock() | |
val observer = object : Observer<T> { | |
override fun onChanged(t: T) { | |
val resultScope = ObserveScope.OnResultScope(this, data, t) | |
context.onResultBlock(resultScope) | |
} | |
} | |
with(data) { | |
observeForever(observer) | |
onDispose { | |
removeObserver(observer) | |
} | |
} | |
} | |
} | |
class ObserveScope<T> { | |
internal var onStartBlock: () -> Unit = {} | |
fun onStart(block: () -> Unit) { | |
onStartBlock = block | |
} | |
internal var onResultBlock: OnResultScope<T>.() -> Unit = {} | |
fun onResult(block: OnResultScope<T>.() -> Unit) { | |
onResultBlock = block | |
} | |
class OnResultScope<T>( | |
private val observer: Observer<T>, | |
private val data: LiveData<T>, | |
val result: T | |
) { | |
fun stopObserving() { | |
data.removeObserver(observer) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment