rxdart icon indicating copy to clipboard operation
rxdart copied to clipboard

BehaviorSubject.isEmpty never finishes when stream is empty

Open orestesgaolin opened this issue 2 years ago • 2 comments

Consider this case:

  test('test', () async {
    final sub = BehaviorSubject<int>();
    final empty = await sub.isEmpty;
    print(empty);
  });

When run it never finishes.

CleanShot 2021-12-01 at 11 09 03@2x

However, when using .hasValue it works just fine:

  test('test', () async {
    final sub = BehaviorSubject<int>();
    final hasValue = await sub.hasValue;
    print(hasValue);
  });

I wonder if this is a known/expected behavior or bug.

orestesgaolin avatar Dec 01 '21 10:12 orestesgaolin

I think you just need to close that BehaviorSubject

frankpepermans avatar Dec 01 '21 10:12 frankpepermans

Stream.isEmpty completes when the Stream emits the first value or done event.

Future<bool> get isEmpty {
  _Future<bool> future = new _Future<bool>();
  StreamSubscription<T> subscription =
      this.listen(null, onError: future._completeError, onDone: () {
    future._complete(true);
  }, cancelOnError: true);
  subscription.onData((_) {
    _cancelAndValue(subscription, future, false);
  });
  return future;
}

Fix:

 test('test', () async {
    final sub = BehaviorSubject<int>();
    sub.close();
    final empty = await sub.isEmpty;
    print(empty);
  });

 test('test', () async {
    final sub = BehaviorSubject<int>();
    sub.add(1);
    final empty = await sub.isEmpty;
    print(empty);
  });

hoc081098 avatar Dec 01 '21 12:12 hoc081098