taler-android

Android apps for GNU Taler (wallet, PoS, cashier)
Log | Files | Refs | README | LICENSE

Event.kt (1762B)


      1 /*
      2  * This file is part of GNU Taler
      3  * (C) 2020 Taler Systems S.A.
      4  *
      5  * GNU Taler is free software; you can redistribute it and/or modify it under the
      6  * terms of the GNU General Public License as published by the Free Software
      7  * Foundation; either version 3, or (at your option) any later version.
      8  *
      9  * GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
     10  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     11  * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
     12  *
     13  * You should have received a copy of the GNU General Public License along with
     14  * GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     15  */
     16 
     17 package net.taler.common
     18 
     19 import androidx.lifecycle.LiveData
     20 import androidx.lifecycle.Observer
     21 import java.util.concurrent.atomic.AtomicBoolean
     22 
     23 /**
     24  * Used as a wrapper for data that is exposed via a [LiveData] that represents an one-time event.
     25  */
     26 open class Event<out T>(private val content: T) {
     27 
     28     private val isConsumed = AtomicBoolean(false)
     29 
     30     /**
     31      * Returns the content and prevents its use again.
     32      */
     33     fun getIfNotConsumed(): T? {
     34         return if (isConsumed.compareAndSet(false, true)) content else null
     35     }
     36 
     37     fun getEvenIfConsumedAlready(): T {
     38         return content
     39     }
     40 
     41 }
     42 
     43 fun <T> T.toEvent() = Event(this)
     44 
     45 /**
     46  * An [Observer] for [Event]s, simplifying the pattern of checking if the [Event]'s content has
     47  * already been consumed.
     48  *
     49  * [onEvent] is *only* called if the [Event]'s contents has not been consumed.
     50  */
     51 class EventObserver<T>(private val onEvent: (T) -> Unit) : Observer<Event<T>> {
     52     override fun onChanged(value: Event<T>) {
     53         value.getIfNotConsumed()?.let { onEvent(it) }
     54     }
     55 }