Last active
March 6, 2022 08:30
-
-
Save MelbourneDeveloper/2dc63fdd613df3a0567aa025daa40651 to your computer and use it in GitHub Desktop.
My Version of Bloc
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:flutter/foundation.dart'; | |
class Bloc<T> { | |
late T _state; | |
final T initialState; | |
late final Future<T> Function(T state, BlocEvent event)? _eventHandler; | |
late final T Function(T state, BlocEvent event)? _eventHandlerSync; | |
final StreamController<T> streamController = StreamController<T>.broadcast(); | |
Bloc(this.initialState, this._eventHandler, this._eventHandlerSync) { | |
_state = initialState; | |
} | |
Bloc.async(this.initialState, this._eventHandler) { | |
_state = initialState; | |
} | |
Bloc.sync(this.initialState, this._eventHandlerSync) { | |
_state = initialState; | |
} | |
Stream<T> get stream => streamController.stream; | |
Future<T> addEvent(BlocEvent event) async { | |
_state = await _eventHandler!(_state, event); | |
streamController.sink.add(_state); | |
return _state; | |
} | |
T addEventSync(BlocEvent event) { | |
_state = _eventHandlerSync!(_state, event); | |
streamController.sink.add(_state); | |
return _state; | |
} | |
void dispose() { | |
streamController.close(); | |
} | |
} | |
@immutable | |
class BlocEvent {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment