Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement