SHARE
TWEET

Untitled

a guest Apr 18th, 2019 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class SingleLiveEvent<T> : MutableLiveData<T>() {
  2.  
  3.     private val mPending = AtomicBoolean(false)
  4.  
  5.     @MainThread
  6.     override fun observe(owner: LifecycleOwner, observer: Observer<T>) {
  7.  
  8.         if (hasActiveObservers()) {
  9.             Log.w(TAG, "Multiple observers registered but only one will be notified of changes.")
  10.         }
  11.  
  12.         // Observe the internal MutableLiveData
  13.         super.observe(owner, Observer<T> { t ->
  14.             if (mPending.compareAndSet(true, false)) {
  15.                 observer.onChanged(t)
  16.             }
  17.         })
  18.     }
  19.  
  20.     @MainThread
  21.     override fun setValue(@Nullable t: T?) {
  22.         mPending.set(true)
  23.         super.setValue(t)
  24.     }
  25.  
  26.     /**
  27.      * Used for cases where T is Void, to make calls cleaner.
  28.      */
  29.     @MainThread
  30.     fun call() {
  31.         value = null
  32.     }
  33.  
  34.     companion object {
  35.  
  36.         private const val TAG = "SingleLiveEvent"
  37.     }
  38. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top