Last active
January 24, 2020 04:22
-
-
Save vamjakuldip/c7280cc8da47132edd410b42a4faa9cc to your computer and use it in GitHub Desktop.
Event Msg Helper. Listen only one Event for LiveData
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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