wrap<U> method

  1. @override
BufferedBaseBeacon<T> wrap<U>(
  1. ReadableBeacon<U> target, {
  2. dynamic then(
    1. BufferedBaseBeacon<T> p1,
    2. U p2
    )?,
  3. bool startNow = true,
})
inherited

Wraps a ReadableBeacon and comsumes its values

Supply a (then) function to customize how the emitted values are processed.

NB: If no then function is provided, the value type of the target must be the same as the wrapper beacon.

Example:

var bufferBeacon = Beacon.bufferedCount<int>(10);
var count = Beacon.writable(5);

// Wrap the bufferBeacon with the readableBeacon and provide a custom transformation.
bufferBeacon.wrap(count, then: (beacon, value) {
  // Custom transformation: Add the value twice to the buffer.
  beacon.add(value);
  beacon.add(value);
});

print(bufferBeacon.buffer); // Outputs: [5, 5]

count.value = 10;

print(bufferBeacon.buffer); // Outputs: [5, 5, 10, 10]

Implementation

@override
BufferedBaseBeacon<T> wrap<U>(
  ReadableBeacon<U> target, {
  Function(BufferedBaseBeacon<T> p1, U p2)? then,
  bool startNow = true,
}) {
  if (_wrapped.containsKey(target.hashCode)) return this;

  if (then == null && U != T) {
    throw WrapTargetWrongTypeException();
  }

  final fn = then ?? ((b, val) => b.add(val as T));

  final unsub = target.subscribe((val) {
    fn(this, val);
  }, startNow: startNow);

  _wrapped[target.hashCode] = unsub;

  return this;
}