Skip to content

Instantly share code, notes, and snippets.

@gavindoughtie
Created September 25, 2017 17:50
Show Gist options
  • Save gavindoughtie/482ade0647531a9e0cb287e5fe41753d to your computer and use it in GitHub Desktop.
Save gavindoughtie/482ade0647531a9e0cb287e5fe41753d to your computer and use it in GitHub Desktop.
stream multiplexing
import 'package:flutter/material.dart';
import 'dart:async';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
typedef S ReduceFn<S, T>(S stream, T input);
StreamTransformer makeReduceTransformer(reduceFn, seed) {
var state = seed;
return new StreamTransformer.fromHandlers(handleData: (s, sink) {
state = reduceFn(state, s);
sink.add(state);
});
}
class _MyHomePageState extends State<MyHomePage> {
Stream<int> _counterStream;
Stream<String> _fizzBuzzStream;
StreamController<Null> _clickStreamController =
new StreamController<Null>.broadcast(sync: true);
@override
void initState() {
super.initState();
int stateFunc(int previous, int input) {
return previous + input;
}
final internalStateStream = _clickStreamController.stream
.map((_) => 1)
.transform(makeReduceTransformer(stateFunc, 0));
StreamController<int> fizzBuzzController =
new StreamController<int>(sync: true);
StreamController<int> stateStreamController =
new StreamController<int>(sync: true);
internalStateStream.listen((val) {
fizzBuzzController.add(val);
stateStreamController.add(val);
});
_fizzBuzzStream = fizzBuzzController.stream.map((int val) {
var output = new StringBuffer('$val:');
if (val % 3 == 0) {
output.write('fizz');
}
if (val % 5 == 0) {
output.write('buzz');
}
return output.toString();
});
_counterStream = stateStreamController.stream;
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new StreamBuilder(
stream: _counterStream,
builder: (context, snapshot) => new Text(
'${snapshot.data ?? 0}',
style: Theme.of(context).textTheme.display1,
),
),
new StreamBuilder(
stream: _fizzBuzzStream,
builder: (context, snapshot) => new Text(
snapshot.data ?? '--',
style: Theme.of(context).textTheme.display2,
),
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: () => _clickStreamController.add(null),
tooltip: 'Increment',
child: new Icon(Icons.add),
));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment