The Stream can guarantee the order of the data.
Stream acts like a queue.
Stream Example
Let's take a look at a simple example.
import 'dart:async';
void main() async {
var stream = streamSend(10);
var sum = await streamReceive(stream);
print('Sum: $sum');
}
Stream<int> streamSend(int to) async* {
for (int i = 1; i <= to; i++) {
print('Sent: $i');
yield i;
}
}
Future<int> streamReceive(Stream<int> stream) async {
var sum = 0;
await for (var value in stream) {
print('Received: $value');
sum += value;
}
return sum;
}
This example sends integer data from 1 to 10 asynchronously using yield.
And, it receives the data and accumulates it.
Properties and Methods of Stream
The Stream has useful methods.
void main() {
var stream = Stream.fromIterable([1, 2, 3, 4, 5]);
stream.first.then((value) => print('first: $value'));
// 1
stream = Stream.fromIterable([1, 2, 3, 4, 5]);
stream.last.then((value) => print('last: $value'));
// 5
stream = Stream.fromIterable([1, 2, 3, 4, 5]);
stream.isEmpty.then((value) => print('isEmpty: $value'));
// false
stream = Stream.fromIterable([1, 2, 3, 4, 5]);
stream.length.then((value) => print('length: $value'));
// 5
}
As you can see from the above example, every time I use the stream, I created stream data.
It is because the stream data is removed once it is used.
fromIterable(Iterable<T> elements)
This method is one of the constructors of the Stream class.
This method creates stream data from iterable data.
Future<T> first
This property contains the first element of the stream.
Future<T> last
This property contains the last element of the stream.
Future<bool> isEmpty
This property contains whether the stream is empty.
Future<int> length
This property contains the number of elements in the stream.
'Dart (Flutter)' 카테고리의 다른 글
[Flutter] Adding Image to Flutter Application (0) | 2022.03.26 |
---|---|
[Flutter] Life Cycle (0) | 2022.03.23 |
[Dart] Handling JSON (0) | 2022.03.12 |
[Flutter] Getting Started on Android Studio (0) | 2022.02.27 |
[Flutter] Getting Started on VSCode (0) | 2022.02.27 |
댓글