Skip to content

Instantly share code, notes, and snippets.

@arok
Created June 25, 2019 09:30
Show Gist options
  • Save arok/cbf9ff284ccf5a97af123a1a26cd6215 to your computer and use it in GitHub Desktop.
Save arok/cbf9ff284ccf5a97af123a1a26cd6215 to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
typedef CombineLatestBlocWidgetBuilder<S1, S2> = Widget Function(BuildContext context, S1 state1, S2 state2);
class CombineLatestBlocBuilder<E1, S1, E2, S2> extends StatefulWidget {
final Bloc<E1, S1> bloc1;
final Bloc<E2, S2> bloc2;
final CombineLatestBlocWidgetBuilder<S1, S2> builder;
const CombineLatestBlocBuilder({Key key, this.bloc1, this.bloc2, this.builder}) : super(key: key);
Widget build(BuildContext context, S1 state1, S2 state2) => builder(context, state1, state2);
@override
_CombineLatestBlocBuilderState<E1, S1, E2, S2> createState() => _CombineLatestBlocBuilderState<E1, S1, E2, S2>();
}
class _CombineLatestBlocBuilderState<E1, S1, E2, S2> extends State<CombineLatestBlocBuilder<E1, S1, E2, S2>> {
StreamSubscription<S1> _subscription1;
StreamSubscription<S2> _subscription2;
S1 _state1;
S2 _state2;
@override
void initState() {
super.initState();
_state1 = widget.bloc1.currentState;
_subscribe1();
_state2 = widget.bloc2.currentState;
_subscribe2();
}
@override
void didUpdateWidget(CombineLatestBlocBuilder<E1, S1, E2, S2> oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.bloc1.state != widget.bloc1.state) {
if (_subscription1 != null) {
_subscription1.cancel();
_state1 = widget.bloc1.currentState;
}
_subscribe1();
}
if (oldWidget.bloc2.state != widget.bloc2.state) {
if (_subscription2 != null) {
_subscription2.cancel();
_state2 = widget.bloc2.currentState;
}
_subscribe2();
}
}
@override
Widget build(BuildContext context) => widget.build(context, _state1, _state2);
@override
void dispose() {
_unsubscribe1();
_unsubscribe2();
super.dispose();
}
void _subscribe1() {
if (widget.bloc1.state != null) {
_subscription1 = widget.bloc1.state.skip(1).listen((S1 state) {
setState(() {
_state1 = state;
});
});
}
}
void _subscribe2() {
if (widget.bloc2.state != null) {
_subscription2 = widget.bloc2.state.skip(1).listen((S2 state) {
setState(() {
_state2 = state;
});
});
}
}
void _unsubscribe1() {
if (_subscription1 != null) {
_subscription1.cancel();
_subscription1 = null;
}
}
void _unsubscribe2() {
if (_subscription2 != null) {
_subscription2.cancel();
_subscription2 = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment