Reputation: 51
I want to display an alert with a message using live data. The problem I have is whenever the activity is resumed the alert pops up again. Any hints?
Upvotes: 4
Views: 5215
Reputation: 1885
You could use a custom live event that is triggered only once. This discussion has already took place on Android's Architecture Google Samples Repository. Here's a proposed solution I like.
In case you need it in kotlin, there it goes:
class SingleLiveEvent<T>: MutableLiveData<T>() {
private val pending = AtomicBoolean(false)
@MainThread
override fun observe(owner: LifecycleOwner, observer: Observer<T>) {
if (hasActiveObservers()) {
Log.w(TAG, "Multiple observers registered but only one will be notified of changes.")
}
// Observe the internal MutableLiveData
super.observe(owner, Observer<T> { t ->
if (pending.compareAndSet(true, false)) {
observer.onChanged(t)
}
})
}
@MainThread
override fun setValue(@Nullable t: T?) {
pending.set(true)
super.setValue(t)
}
/**
* Used for cases where T is Void, to make calls cleaner.
*/
@MainThread
fun call() {
value = null
}
companion object {
private val TAG = "SingleLiveEvent"
}
}
Using this it won't trigger you dialogs twice unless you call yourLiveData.value = newValue
again.
Hope it helps.
Upvotes: 6
Reputation: 6282
Set a boolean isShown = false;
When you show the dialog set it to true and save it to Shared preferences. show the dialog only isShown is false.
Upvotes: 0