-
Notifications
You must be signed in to change notification settings - Fork 0
Wrapping the live data in the Util Event class
Devrath edited this page Jul 11, 2021
·
1 revision
- This is very useful in case of handling the live data.
- We make the network request and get either the data in the success state of the resource object we defined earlier of the error state.
- Problem with this approach is that, say there is an error state and we use snack bar to display the error and now we rotate the device and during this, the snack bar is displayed again.
- Now Using this generic event class we can make sure the event is emitted only once.
code snippet
private val _images = MutableLiveData<Event<Resource<ImageResponse>>>()
val images: LiveData<Event<Resource<ImageResponse>>> = _images
Event.kt
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
}