[Android] LiveEvent class, for single events with LiveData
Geoffrey Métais
git at videolan.org
Wed Apr 4 18:36:21 CEST 2018
vlc-android | branch: master | Geoffrey Métais <geoffrey.metais at gmail.com> | Wed Apr 4 14:16:48 2018 +0200| [f19c89eccf014854062824352f32aba6f8e8f972] | committer: Geoffrey Métais
LiveEvent class, for single events with LiveData
> https://code.videolan.org/videolan/vlc-android/commit/f19c89eccf014854062824352f32aba6f8e8f972
---
vlc-android/src/org/videolan/vlc/util/LiveEvent.kt | 32 ++++++++++++++++++++++
1 file changed, 32 insertions(+)
diff --git a/vlc-android/src/org/videolan/vlc/util/LiveEvent.kt b/vlc-android/src/org/videolan/vlc/util/LiveEvent.kt
new file mode 100644
index 000000000..a58b3a6ee
--- /dev/null
+++ b/vlc-android/src/org/videolan/vlc/util/LiveEvent.kt
@@ -0,0 +1,32 @@
+package org.videolan.vlc.util
+
+import android.arch.lifecycle.LifecycleOwner
+import android.arch.lifecycle.MutableLiveData
+import android.arch.lifecycle.Observer
+import android.support.annotation.MainThread
+import android.support.annotation.Nullable
+import android.util.Log
+import java.util.concurrent.atomic.AtomicBoolean
+
+private const val TAG = "VLC/LiveEvent"
+
+class LiveEvent<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)
+ }
+
+ @MainThread
+ fun call() {
+ value = null
+ }
+}
\ No newline at end of file
More information about the Android
mailing list