Skip to content

Instantly share code, notes, and snippets.

@JoseAlcerreca
Created April 26, 2018 12:14
Show Gist options
  • Save JoseAlcerreca/e0bba240d9b3cffa258777f12e5c0ae9 to your computer and use it in GitHub Desktop.
Save JoseAlcerreca/e0bba240d9b3cffa258777f12e5c0ae9 to your computer and use it in GitHub Desktop.
An Observer for Events, simplifying the pattern of checking if the Event's content has already been handled.
/**
* An [Observer] for [Event]s, simplifying the pattern of checking if the [Event]'s content has
* already been handled.
*
* [onEventUnhandledContent] is *only* called if the [Event]'s contents has not been handled.
*/
class EventObserver<T>(private val onEventUnhandledContent: (T) -> Unit) : Observer<Event<T>> {
override fun onChanged(event: Event<T>?) {
event?.getContentIfNotHandled()?.let { value ->
onEventUnhandledContent(value)
}
}
}
@Zhuinden
Copy link

@gmk57 this is true. Theoretically it'd be possible to either expose setPaused from command-queue and/or provide a "minimumSubscriberCount" (working name) that would make it so that under 3 subscribers the EventEmitter is paused

@Dzendo
Copy link

Dzendo commented Jun 19, 2021

inline fun <T> LiveData<Event<T>>.observeEvent(owner: LifecycleOwner, crossinline onEventUnhandledContent: (T) -> Unit) {
    observe(owner, Observer { it?.getContentIfNotHandled()?.let(onEventUnhandledContent) })
}

I finished it like this. It seems to work correctly. What's your opinion?

inline fun LiveData<Event>.observeEvent(owner: LifecycleOwner, crossinline onEventUnhandledContent: (T) -> Unit) {
observe(owner) { it?.getContentIfNotHandled()?.let(onEventUnhandledContent) }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment