Skip to content

Commit

Permalink
feat: Add Event for single-use LiveData's
Browse files Browse the repository at this point in the history
  • Loading branch information
percula committed Oct 2, 2019
1 parent b6e5e87 commit 9eb4c97
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
27 changes: 27 additions & 0 deletions library/src/main/java/dev/percula/ktx/event/Event.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package dev.percula.ktx.event

/**
* Used as a wrapper for data that is exposed via a LiveData that represents an event (one-time use).
*/
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
}
15 changes: 15 additions & 0 deletions library/src/main/java/dev/percula/ktx/event/EventObserver.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package dev.percula.ktx.event

import androidx.lifecycle.Observer

/**
* 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 { onEventUnhandledContent }
}
}

0 comments on commit 9eb4c97

Please sign in to comment.