Created
March 25, 2020 11:26
-
-
Save belozerskiy/34a12e32914bd817d828785d89b76783 to your computer and use it in GitHub Desktop.
play with dart 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
class Range { | |
final StreamController _controller = StreamController(); | |
final int from; | |
final int to; | |
int seconds; | |
Stream<dynamic> get stream => _controller.stream.asBroadcastStream(); | |
Range({ this.from = 1, this.to = 0 }) : assert(from != null), assert(to != null) { | |
genNormalRange(); | |
} | |
Range.periodic({ this.seconds, this.from = 1, this.to = 0 }): assert(wait != null), assert(from != null), assert(to != null) { | |
genPeriodicRange(); | |
} | |
Future genPeriodicRange() async { | |
for(var i = from; i <= to; i++) { | |
await wait(Duration(seconds: seconds)); | |
_controller.sink.add(i); | |
} | |
_controller.close(); | |
} | |
void genNormalRange() { | |
for(var i = from; i <= to; i++) { | |
_controller.sink.add(i); | |
} | |
_controller.close(); | |
} | |
} | |
Future wait(Duration duration) { | |
Completer completer = Completer(); | |
Timer(duration, completer.complete); | |
return completer.future; | |
} | |
void main() { | |
final periodicRange$ = Range.periodic(seconds: 1, to: 10).stream; | |
periodicRange$.listen((i) => print(i)); | |
periodicRange$.where((i) => i % 2 == 0).listen((i) => print(i)); | |
periodicRange$.where((i) => i % 2 != 0).listen((i) => print(i)); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment