finexo
finexo

Reputation: 25

Repeat stream when done

hello I am using a stream on my app to get some data. at the end of data the stream stop, what i want is to start again every time stream is done

  final stream =  Stream.periodic(kDuration, (count) => count)
      .take(kLocations.length);

stream.listen((value) => newLocationUpdate(value)

I was searching for hours and didnt find a good solution

Upvotes: 2

Views: 468

Answers (1)

cameron1024
cameron1024

Reputation: 10136

Calling .take(kLocations.length) will cause the stream to close once that number of elements have been emitted. For example:

final stream = Stream.periodic(kDuration, (count) => count).take(3);
stream.listen(print);  // prints 0, 1, 2, then stops

If instead, you want this to repeat (i.e. emit 0, 1, 2, 0, 1, 2, etc), you can use the modulus operator (%):

final stream = Stream.periodic(kDuration, (count) => count % 3);
stream.listen(print);  // prints 0, 1, 2, 0, 1, 2, 0, 1, 2, ...

Upvotes: 2

Related Questions