Skip to content

Instantly share code, notes, and snippets.

@phamducminh
Forked from JoseAlcerreca/EventObserver.kt
Created April 10, 2020 02:48
Show Gist options
  • Save phamducminh/d682ca41600a8133054614dc7bc1fc2a to your computer and use it in GitHub Desktop.
Save phamducminh/d682ca41600a8133054614dc7bc1fc2a 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)
}
}
}
@phamducminh
Copy link
Author

Java implementation:

import androidx.lifecycle.Observer;

public class EventObserver<T> implements Observer<Event<T>> {

    private Listener<T> listener;

    public EventObserver(Listener<T> listener) {
        this.listener = listener;
    }

    @Override
    public void onChanged(Event<T> event) {
        if (event != null){
            T content = event.getContentIfNotHandled();
            if (content != null){
                listener.onEventUnhandledContent(content);
            }
        }
    }

    public interface Listener<T> {
        void onEventUnhandledContent(T t);
    }
}

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