Skip to content

Instantly share code, notes, and snippets.

@fluxtah
Created March 2, 2020 10:21
Show Gist options
  • Save fluxtah/87b149238cd2edc9d56e6edbf2f342b6 to your computer and use it in GitHub Desktop.
Save fluxtah/87b149238cd2edc9d56e6edbf2f342b6 to your computer and use it in GitHub Desktop.
@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