Commit 3681ee89 authored by Sebastian Kaspari's avatar Sebastian Kaspari
Browse files

Issue #1843: Add optional callback to Consumable.

parent ca9006d0
......@@ -6,9 +6,13 @@ package mozilla.components.support.base.observer
/**
* A generic wrapper for values that can get consumed.
*
* @param value The value to be wrapped.
* @param onConsume A callback that gets invoked if the wrapped value gets consumed.
*/
class Consumable<T> private constructor(
internal var value: T?
internal var value: T?,
private val onConsume: (() -> Unit)? = null
) {
/**
* Invokes the given lambda and marks the value as consumed if the lambda returns true.
......@@ -17,6 +21,7 @@ class Consumable<T> private constructor(
fun consume(consumer: (value: T) -> Boolean): Boolean {
return if (value?.let(consumer) == true) {
value = null
onConsume?.invoke()
true
} else {
false
......@@ -34,6 +39,7 @@ class Consumable<T> private constructor(
return if (results.contains(true)) {
this.value = null
onConsume?.invoke()
true
} else {
false
......@@ -50,7 +56,7 @@ class Consumable<T> private constructor(
/**
* Creates a new Consumable wrapping the given value.
*/
fun <T> from(value: T): Consumable<T> = Consumable(value)
fun <T> from(value: T, onConsume: (() -> Unit)? = null): Consumable<T> = Consumable(value, onConsume)
/**
* Creates a new Consumable stream for the provided values.
......
......@@ -208,6 +208,50 @@ class ConsumableTest {
assertFalse(consumable.isConsumed())
}
@Test
fun `callback gets invoked if value gets consumed`() {
var callbackInvoked = false
val consumable = Consumable.from(42) {
callbackInvoked = true
}
consumable.consume { false }
assertFalse(callbackInvoked)
consumable.consume { true }
assertTrue(callbackInvoked)
}
@Test
fun `callback gets invoked if one consumer in list consumes value`() {
var callbackInvoked = false
val consumable = Consumable.from(42) {
callbackInvoked = true
}
consumable.consumeBy(listOf<(Int) -> Boolean>(
{ false },
{ false },
{ false },
{ false }
))
assertFalse(callbackInvoked)
consumable.consumeBy(listOf<(Int) -> Boolean>(
{ false },
{ false },
{ true },
{ false }
))
assertTrue(callbackInvoked)
}
@Test
fun `stream gets consumed in insertion order`() {
val stream = Consumable.stream(1, 2, 3)
......
......@@ -45,7 +45,16 @@ permalink: /changelog/
language specific headers to websites. Implementation in `browser-engine-gecko-nightly`.
* **service-firefox-accounts**
* The service no longer accepts a `successPath` option. Instead the service uses the OAuth `redirectUri`.
* The service no longer accepts a `successPath` option. Instead the service uses the OAuth `redirectUri`.
* **support-base**
* Added optional callback to `Consumable` to get invoked once value gets consumed:
```kotlin
val consumable = Consumable.from(42) {
// Value got consumed.
}
```
# 0.49.0
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment