Last active
January 31, 2021 15:43
-
-
Save addeeandra/5cafbbd00646393276c2b89856c11bdc to your computer and use it in GitHub Desktop.
ViewModel SingleLiveEvent - Wraps the MutableLiveData<ActionEvent<T>>
This file contains hidden or 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
class Event<out T>(private val content: T) { | |
var hasBeenUsed = false | |
private set | |
fun getContentIfNotUsed(): T? { | |
return if (hasBeenUsed) { | |
null | |
} else { | |
hasBeenUsed = true | |
content | |
} | |
} | |
fun peekContent(): T = content | |
} |
This file contains hidden or 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
open class LiveEvent<T> { | |
val action: MutableLiveData<ActionEvent<T>> = MutableLiveData() | |
fun observe(lifecycleOwner: LifecycleOwner, callback: (data: T) -> Unit) { | |
action.observe(lifecycleOwner, Observer { | |
action.value?.let { | |
if (!it.hasBeenUsed) { | |
callback(it.getContentIfNotUsed() ?: it.peekContent()) | |
} | |
} | |
}) | |
} | |
} | |
fun <T> SingleEvent<T>.post(value: T) { | |
this.action.postValue(Event(value)) | |
} | |
fun SingleEvent<Unit>.post() { | |
this.action.postValue(Event(Unit)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment