Created
May 28, 2019 02:49
-
-
Save felangel/0d98c1fe3925aacb92c614fe9e68ec9f to your computer and use it in GitHub Desktop.
[flutter_timer] Timer Bloc resume event
This file contains 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'; | |
import 'package:meta/meta.dart'; | |
import 'package:bloc/bloc.dart'; | |
import 'package:flutter_timer/bloc/bloc.dart'; | |
import 'package:flutter_timer/ticker.dart'; | |
class TimerBloc extends Bloc<TimerEvent, TimerState> { | |
final Ticker _ticker; | |
final int _duration = 60; | |
StreamSubscription<int> _tickerSubscription; | |
TimerBloc({@required Ticker ticker}) | |
: assert(ticker != null), | |
_ticker = ticker; | |
@override | |
TimerState get initialState => Ready(_duration); | |
@override | |
Stream<TimerState> mapEventToState( | |
TimerEvent event, | |
) async* { | |
if (event is Start) { | |
yield* _mapStartToState(event); | |
} else if (event is Pause) { | |
yield* _mapPauseToState(event); | |
} else if (event is Resume) { | |
yield* _mapResumeToState(event); | |
} else if (event is Tick) { | |
yield* _mapTickToState(event); | |
} | |
} | |
@override | |
void dispose() { | |
_tickerSubscription?.cancel(); | |
super.dispose(); | |
} | |
Stream<TimerState> _mapStartToState(Start start) async* { | |
yield Running(start.duration); | |
_tickerSubscription?.cancel(); | |
_tickerSubscription = _ticker.tick(ticks: start.duration).listen( | |
(duration) { | |
dispatch(Tick(duration: duration)); | |
}, | |
); | |
} | |
Stream<TimerState> _mapPauseToState(Pause pause) async* { | |
final state = currentState; | |
if (state is Running) { | |
_tickerSubscription?.pause(); | |
yield Paused(state.duration); | |
} | |
} | |
Stream<TimerState> _mapResumeToState(Resume pause) async* { | |
final state = currentState; | |
if (state is Paused) { | |
_tickerSubscription?.resume(); | |
yield Running(state.duration); | |
} | |
} | |
Stream<TimerState> _mapTickToState(Tick tick) async* { | |
yield tick.duration > 0 ? Running(tick.duration) : Finished(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment