rxdart icon indicating copy to clipboard operation
rxdart copied to clipboard

ValueStream.map should return ValueStream (?)

Open Albert221 opened this issue 2 years ago • 1 comments

Hello,

shouldn't ValueStream<T>.map(U Function(T)) return ValueStream<U> instead of Stream<U>?

I'd like to have an easy way to map the value stream while preserving the value stream characteristics.

This is what I used instead: https://gist.github.com/Albert221/c0da244cec07f7f2de317d19d9a56a27

Probably related to #625.

Albert221 avatar Jul 31 '23 09:07 Albert221

@Albert221 I love your DelegatingStream solution to this problem, really clean and works even when there are no subscriptions to the stream.

We currently use a solution like this, not sure if it would be possible to change the behavior of the map function, as it is defined for the Stream class, and ValueStream is also a Stream. And adding function like mapValue might add too much complexity to the already not very beginner-friendly rxdart, but definitely something to discuss

extension ValueStreamExtensions<T> on ValueStream<T> {
  ValueStream<U> mapValue<U>(U Function(T value) mapper) {
    return MapValueStream(this, mapper);
  }
}

class MapValueStream<T, U> extends StreamView<U> implements ValueStream<U> {
  MapValueStream(this._source, this._mapper) : super(_source.map(_mapper));

  final ValueStream<T> _source;
  final U Function(T) _mapper;

  @override
  U get value => _mapper(_source.value);

  @override
  U? get valueOrNull {
    if (_source.value case final value?) {
      return _mapper(value);
    }

    return null;
  }

  @override
  bool get hasValue => _source.hasValue;

  @override
  Object get error => _source.error;

  @override
  Object? get errorOrNull => _source.errorOrNull;

  @override
  bool get hasError => _source.hasError;

  @override
  StackTrace? get stackTrace => _source.stackTrace;
}

mrRedSun avatar Jan 01 '25 23:01 mrRedSun