Skip to content

Instantly share code, notes, and snippets.

@vamjakuldip
Last active January 24, 2020 04:22
Show Gist options
  • Save vamjakuldip/c7280cc8da47132edd410b42a4faa9cc to your computer and use it in GitHub Desktop.
Save vamjakuldip/c7280cc8da47132edd410b42a4faa9cc to your computer and use it in GitHub Desktop.
Event Msg Helper. Listen only one Event for LiveData
package com.vk.android.utils
import androidx.lifecycle.Observer
open class EventMsg<out T>(private val content: T) {
var hasBeenHandled = false
private set // Allow external read but not write
fun getContentIfNotHandled(): T? {
return if (hasBeenHandled) {
null
} else {
hasBeenHandled = true
content
}
}
fun peekContent(): T = content
}
class EventObserver<T>(private val onEventUnhandledContent: (T) -> Unit) : Observer<EventMsg<T>> {
override fun onChanged(eventMsg: EventMsg<T>?) {
eventMsg?.getContentIfNotHandled()?.let {
onEventUnhandledContent(it)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment