Skip to content

Instantly share code, notes, and snippets.

@JoseAlcerreca
Created April 26, 2018 10:25
Show Gist options
  • Save JoseAlcerreca/5b661f1800e1e654f07cc54fe87441af to your computer and use it in GitHub Desktop.
Save JoseAlcerreca/5b661f1800e1e654f07cc54fe87441af to your computer and use it in GitHub Desktop.
An event wrapper for data that is exposed via a LiveData that represents an event.
/**
* Used as a wrapper for data that is exposed via a LiveData that represents an event.
*/
open class Event<out T>(private val content: T) {
var hasBeenHandled = false
private set // Allow external read but not write
/**
* Returns the content and prevents its use again.
*/
fun getContentIfNotHandled(): T? {
return if (hasBeenHandled) {
null
} else {
hasBeenHandled = true
content
}
}
/**
* Returns the content, even if it's already been handled.
*/
fun peekContent(): T = content
}
@feinstein
Copy link

feinstein commented Sep 3, 2018

I read your article here, but I don't think this code can provide some of the benefits you talk about, please correct me if I am wrong.

1 - You say that SingleLiveEvent isn't a perfect solution because:

it’s restricted to one observer. If you inadvertently add more than one, only one will be called and there’s no guarantee of which one.

But I can't see how this Event class is going to be much different than that. It will indeed be sent to all the Observers that register to observe this Event, but as soon as the first Observer calls getContentIfNotHandled(), all others will lose track if they have received this Event before, or not.

If the Observer choose to use peekContent() instead, it can retreive the Event value, but still it has no clue if it did catch this Event in the past, or didn't.

So how's this the recommended solution for multiple Observers?

I think a better suited option would be to have a Map holding a boolean for each key, whereas the key can be a String or the Class of the Observer (I think that using the Observer himself could lead to memory leaks maybe? I am not sure), and the boolean just informs if this Observer has got the content or not. This way, the Observer will have to pass it's key to get the content.

2 - Shouldn’t hasBeenHandled be atomic for thread safety?

@nicol-ograve
Copy link

This approach avoid cases in which multiple observers exists but only one is the effective consumer. With SingleLiveEvent other observers like a Logger, could prevent the main consumer to access the event. In this way there is a separation between consuming observers (that in the majority of cases will be just one) and non-consuming ones

@feinstein
Copy link

Yes, but this separation was never the point of this class, at least not according to his article.

Copy link

ghost commented Sep 24, 2018

Same question as @feinstein

@rvdsoft
Copy link

rvdsoft commented Oct 10, 2018

@feinstein @raiytu4
I have created an improved version of @JoseAlcerreca's SingleLiveEvent that supports multiple observers. No need for a custom observer class or value wrapper.

public class SingleLiveEvent<T> extends MutableLiveData<T> {

    private LiveData<T> liveDataToObserve;
    private final AtomicBoolean mPending = new AtomicBoolean(false);

    public SingleLiveEvent() {
        final MediatorLiveData<T> outputLiveData = new MediatorLiveData<>();
        outputLiveData.addSource(this, currentValue -> {
            outputLiveData.setValue(currentValue);
            mPending.set(false);
        });
        liveDataToObserve = outputLiveData;
    }

    @MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
        liveDataToObserve.observe(owner, t -> {
            if(mPending.get()) {
                observer.onChanged(t);
            }
        });
    }

    @MainThread
    public void setValue(T value) {
        mPending.set(true);
        super.setValue(value);
    }
}

@ipcjs
Copy link

ipcjs commented Oct 19, 2018

@rvdsoft you code have a bug.
if i observe the singleLiveEvent after send event. i can't receive the event.

@RajaParikshit
Copy link

RajaParikshit commented Oct 24, 2018

This SingleLiveEvent class gives error for androidx

'observe(LifecycleOwner, Observer)' in 'com.busisoft.ezeeoffice.helpers.SingleLiveEvent' clashes with 'observe(LifecycleOwner, Observer<? super T>)' in 'androidx.lifecycle.LiveData'; both methods have same erasure, yet neither overrides the other

@hvsimon
Copy link

hvsimon commented Nov 21, 2018

@rvdsoft you code have a bug.
if i observe the singleLiveEvent after send event. i can't receive the event.

This is intended behavior. It is base on Google's android-architecture sample.

A lifecycle-aware observable that sends only new updates after subscription, used for events like navigation and Snackbar messages.

https://github.com/googlesamples/android-architecture/blob/todo-mvvm-live/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/SingleLiveEvent.java

@schildbach
Copy link

This SingleLiveEvent class gives error for androidx

'observe(LifecycleOwner, Observer)' in 'com.busisoft.ezeeoffice.helpers.SingleLiveEvent' clashes with 'observe(LifecycleOwner, Observer<? super T>)' in 'androidx.lifecycle.LiveData'; both methods have same erasure, yet neither overrides the other

@RajaParikshit Simply adapt to the new signature by adding the ? super.

@ArthurCideron
Copy link

@rvdsoft but in your implementation, the event will be consumed just once, by the first observer that gots hold of it.
I believed that what @feinstein wanted was to be abled to have multiple observers, that each consume the Event once ?

I made up (quickly) something like that below, based on your code and @feinstein suggestion. It seems to work fine but I have to say, it does feel a bit like a hack...

class SingleLiveEvent<T> : MutableLiveData<T>() {

    private val liveDataToObserve: LiveData<T>
    private val pendingMap: MutableMap<Int, Boolean>

    init {
        val outputLiveData = MediatorLiveData<T>()
        outputLiveData.addSource(this) { currentValue ->
            outputLiveData.value = currentValue
        }
        liveDataToObserve = outputLiveData
        pendingMap = HashMap()
    }

    override fun observe(owner: LifecycleOwner, observer: Observer<T>) {

        pendingMap[observer.hashCode()] = false

        // Observe the internal MutableLiveData
        liveDataToObserve.observe(owner, Observer { t ->
            if (pendingMap[observer.hashCode()] == true) { // don't trigger if the observer wasn't registered
                observer.onChanged(t)
                pendingMap[observer.hashCode()] = false
            }
        })
    }

    override fun setValue(t: T?) {
        pendingMap.forEach { pendingMap[it.key] = true }
        super.setValue(t)
    }
}

@OssamaDroid
Copy link

OssamaDroid commented May 3, 2019

@feinstein By using this event wrapper for data, it's possible for multiple observers to observe the live data and they will all get notified with any live data change. What you only have to make sure is creating a new Event object for each Live data's value.

If we consider the example being given in the article, it would be something like:

private val _navigateToDetails = MutableLiveData<Event<String>>()

val navigateToDetails : LiveData<Event<String>>
    get() = _navigateToDetails

private val _navigateToHome = MutableLiveData<Event<String>>()

val navigateToHome : LiveData<Event<String>>
    get() = _navigateToHome

fun userClicksOnItem(itemId: String) {
    _navigateToDetails.value = Event(itemId)
}

fun userClicksOnHomeButton(itemId: String) {
    _navigateToHome.value = Event(itemId)
}

@MrTheGood
Copy link

If you want to use nullable content:

open class Event<out T>(
    private val content: T
) {
    val hasBeenHandled = AtomicBoolean(false)

    fun getContentIfNotHandled(handleContent: (T) -> Unit) {
        if (!hasBeenHandled.get()) {
            hasBeenHandled.set(true)
            handleContent(content)
        }
    }

    fun peekContent() = content
}

@adam-hurwitz
Copy link

adam-hurwitz commented May 24, 2020

For those working with Kotlin Flow I have created an extension function, onEachEvent, using the Event wrapper above. You may find the full explanation and code here.

OnEachEvent.kt

/**
 * Returns a flow which performs the given [action] on each value of the original flow's [Event].
 */
public fun <T> Flow<Event<T?>>.onEachEvent(action: suspend (T) -> Unit): Flow<T> = transform { value ->
    value.getContentIfNotHandled()?.let {
        action(it)
        return@transform emit(it)
    }
}

@choirwire
Copy link

choirwire commented Jan 21, 2021

I thought about a solution that's based on the Event class but enables more than one client to consume an event (each client only once). My current approach is an EventRepeater class which takes an Event from a source LiveData and forwards it to a new (always unconsumed) Event for each client. To prevent the same event is forwarded twice, it will be compared with the previous event object:

class EventRepeater<T>(source: LiveData<Event<T>>) : MediatorLiveData<Event<T>>() {
    var previousEvent: Event<T>? = null
    init {
        addSource(source) { event ->
            if (event !== previousEvent) {
                previousEvent = event
                value = event?.let { Event(it.peekContent()) }
            }
        }
    }
}

@aluv
Copy link

aluv commented Jan 26, 2021

I modified the EventObserver class as well as the Event class. In the EventObserver class I added a secondary constructor that takes a string value to be used by the event class to check whether the event has been consumed by this specific observer (represented by that string value). This string value is passed on to the Event class that uses its presence (or absence) to determine whether to operate as a SingleObservationEvent or as a MultipleObservationEvent.

/**
 * 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> : Observer<Event<T>> {
    private val onEventUnhandledContent: (T) -> Unit
    private var myStr: String? = null

    constructor(onEventUnhandledContent: (T) -> Unit) {
        this.onEventUnhandledContent = onEventUnhandledContent
    }

    constructor(onEventUnhandledContent: (T) -> Unit, str: String) {
        this.onEventUnhandledContent = onEventUnhandledContent
        myStr = str
    }

    override fun onChanged(event: Event<T>?) {
        event?.getIfNotHandled(myStr)?.let { value ->
            onEventUnhandledContent(value)
        }
    }
}


/**
 * Used as a wrapper for data that is exposed via a LiveData that represents an event.
 */
data class Event<out T>(private val content: T) {
    private val hasBeenHandled = AtomicBoolean(false)
    private val lock = ReentrantLock()
    private val handledMap = HashMap<String, Boolean>()

    /**
     * Returns the content and prevents its use again.
     */
    fun getIfNotHandled(str: String? = null): T? {
        var singleEvent = true
        var allowContent = false
        str?.let {
            singleEvent = false
            lock.withLock {
                val handled = handledMap[it]
                if (handled == null) {
                    allowContent = true
                    handledMap[it] = true
                }
            }
        }

        return if (singleEvent) {
            if (hasBeenHandled.getAndSet(true))
                null
            else
                content
        } else {
            if (allowContent)
                content
            else
                null
        }
    }

    /**
     * Returns the content, even if it's already been handled.
     */
    fun peek(): T = content
}

And to use it

  1. Vanilla (Default SingleFire Observable)

         myObservable.observe(
         this, EventObserver(
             onEventUnhandledContent = fun(it: String) { }
             }, myStr = "Observer1"))
    
  2. MultipleObserver

         myObservable.observe(
         this, EventObserver(
             onEventUnhandledContent = fun(it: String) { }
             }))
    

or the lambda version

        myObservable.observe(this, EventObserver{ })

@choirwire
Copy link

That looks nearly like my latest solution. However, I don't use a special EventObserver, since a Kotlin extension function can do the job:

class Event<out T>(private val content: T) {
    private val consumedScopes = HashSet<String>()

    fun isConsumed(scope: String = "") = consumedScopes.contains(scope)

    @MainThread
    fun consume(scope: String = ""): T? {
        return if (isConsumed(scope)) {
            null
        } else {
            consumedScopes.add(scope)
            content
        }
    }

    fun peek(): T = content
}

fun <T> LiveData<Event<T>>.observeEvent(lifecycleOwner: LifecycleOwner, scope: String = "", observer: Observer<T>) {
    observe(lifecycleOwner) { event ->
        event?.consume(scope)?.let { observer.onChanged(it) }
    }
}

// How to use it
myObservable.observeEvent { ... }
myObservable.observeEvent("specialScope") { ... }

@aluv
Copy link

aluv commented Jan 27, 2021

This is so concise.

@gmk57
Copy link

gmk57 commented Feb 21, 2021

In Kotlin, passing events to a single observer is also possible with Channel.receiveAsFlow() and lifecycle-aware collector. Advantages:

  1. Can queue multiple events while observer is inactive (configuration change, app in background, fragment in back stack), with customizable buffer size and onBufferOverflow strategy
  2. Optionally supports null values
  3. No need to wrap data in Event

@abdalin
Copy link

abdalin commented Jun 3, 2021

That looks nearly like my latest solution. However, I don't use a special EventObserver, since a Kotlin extension function can do the job:

class Event<out T>(private val content: T) {
    private val consumedScopes = HashSet<String>()

Adding more syntactic sugar to choirwire's contribution

class Event<out T>(private val content: T) {
    private val consumedScopes by lazy { HashSet<String>() }

    fun isConsumed(scope: String = "") = scope in consumedScopes

    @MainThread
    fun consume(scope: String = ""): T? {
        return content.takeIf { !isConsumed(scope) }?.also { consumedScopes.add(scope) }
    }

    fun peek(): T = content
}

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