Skip to content

Instantly share code, notes, and snippets.

@leocavalcante
Created July 26, 2019 20:54
Show Gist options
  • Save leocavalcante/10a2bbc7a099722d6151e11cded8995d to your computer and use it in GitHub Desktop.
Save leocavalcante/10a2bbc7a099722d6151e11cded8995d to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';
class CounterBloc {
int initialCount = 20;
BehaviorSubject<int> _subjectCounter;
CounterBloc() {
_subjectCounter = new BehaviorSubject<int>.seeded(this.initialCount);
}
Observable<int> get counterObservable => _subjectCounter.stream;
void increment() {
initialCount++;
_subjectCounter.sink.add(initialCount);
}
void dispose() {
_subjectCounter.close();
}
}
void main() => runApp(MyApp());
class StreamText extends StatelessWidget {
final CounterBloc counterBloc;
const StreamText({Key key, this.counterBloc}) : super(key: key);
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: counterBloc.counterObservable,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) =>
Text('${snapshot.data}'),
);
}
}
class MyApp extends StatelessWidget {
final CounterBloc _counterBloc = CounterBloc();
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SafeArea(
child: Column(
children: <Widget>[
StreamText(
counterBloc: _counterBloc,
),
RaisedButton(
onPressed: _counterBloc.increment,
child: Text('Sum'),
)
],
)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment