0

I want to get length of BehaviorSubject's stream, but I can't get it.

test('get stream length', ()async{
    BehaviorSubject<int> subject = new BehaviorSubject(seedValue: 0);

    var act = await subject.stream.length;

    expect(act, 1);
  }); 

How I can get this length?

taross
  • 1
  • 1

1 Answers1

2

The length of a stream can only be known after it is closed. As long as it is not closed it's always possible that another event will be added.

https://api.dartlang.org/stable/2.1.1/dart-async/Stream/length.html

length property

Future<int> length

The number of elements in this stream.

Waits for all elements of this stream. When this stream ends, the returned future is completed with the number of elements.

If this stream emits an error, the returned future is completed with that error, and processing stops.

This operation listens to this stream, and a non-broadcast stream cannot be reused after finding its length.

  test('get stream length', ()async{
    BehaviorSubject<int> subject = new BehaviorSubject(seedValue: 0);

    var actFuture = await subject.stream.length;
    await subject.close();

    expect(actFuture, completion(equals(1));
  }); 
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thank you! I want to know length of stream to get latest value of another stream with ''' anotherStream.elementAt(length); ''' , is this impossible? Should I try to another way? – taross Feb 27 '19 at 09:43
  • You can't get `elementAt(x)` from a stream that easily. What if that element was emitted earlier already? A stream is like a dripping tap. You don't know in advance how many drops will come down. You can collect the drops (in a `List` for example) and then later use them. There might be better ways for your concrete use case but it's not clear what exactly you try to accomplish. – Günter Zöchbauer Feb 27 '19 at 09:49
  • Oh, I see. Thank you. It is really easy to understand. – taross Feb 27 '19 at 13:06
  • I try to add to latest element of List stream in stream, I want to use it like Firestore snapshot. But I might should not be use stream in stream... – taross Feb 27 '19 at 13:16
  • The rxdart package provides lots of functionality to do all kinds of things with streams, but you need to adjust your thinking. A stream is not a collection, it's a series of events stretched over some time or over "infinite" time. – Günter Zöchbauer Feb 27 '19 at 14:02
  • 1
    You are right. I should learn stream... I appreciate for the advice. (and I found `combineLatest2` method, I'll try it.) – taross Feb 27 '19 at 14:36
  • There is a dedicated Gitter channel for rxdart https://gitter.im/ReactiveX/rxdart – Günter Zöchbauer Feb 27 '19 at 14:37