wrap<U> method

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

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
WritableBeacon<T> wrap<U>(
  ReadableBeacon<U> target, {
  Function(WritableBeacon<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 ?? ((wb, val) => wb.set(val as T));

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

  _wrapped[target.hashCode] = unsub;

  return this;
}