Skip to content

Instantly share code, notes, and snippets.

@Vanethos
Created September 26, 2019 05:44
Show Gist options
  • Save Vanethos/a96057ab6fb3e0bf3b0180edf3ec0a8c to your computer and use it in GitHub Desktop.
Save Vanethos/a96057ab6fb3e0bf3b0180edf3ec0a8c to your computer and use it in GitHub Desktop.
class ListBloc extends BaseBloc {
// Streams the lists of items
var _listOfItemsSubject = BehaviorSubject<List<Items>>();
Stream<List<Items>> get listOfItemsStream => _listOfItemsSubject.stream;
// Sink to fetch new data
var _fetchItemsSubject = PublishSubject<Event>();
Sink<Event> get fetchItemsSink => _fetchItemsSubject.sink;
ListBloc(ItemsManager manager) {
// Every time we receive a fetch event, we fetch new items
_fetchItemsSubject.stream
.flatMap((_) => manager.fetchItems())
.listen(_listOfItemsSubject.add, error: (e) => handleError(e));
// When this BLoC is created, we want to have a list of items, so we fetch it
_fetchItemsSubject.add(Event())
}
}
class CategoryBloc extends BaseBloc {
// Stream to stream the list, and Sink to add the list when the BLoC is created
var _listOfItemsSubject = BehaviorSubject<List<Items>>();
Sink<List<Items>> get listOfItemsSink => _listOfItemsSubject.sink;
Stream<List<Items>> get listOfItemsStream => _listOfItemsSubject.stream;
CategoryBloc() {
// ...
}
}
class AddBloc extends BaseBloc {
// Sink to receive the event to add a new item
var _addItemSubject = PublishSubject<Input>();
Sink<Input> get addItemSink => _addItemSubject.sink;
// Stream with the response from the server, the new item
var _addResponseSubject = PublishSubject<Item>();
Stream<Item> get addResponseStream => _addResponseSubject.stream;
AddBloc(ItemsManager manager) {
// When we receive the new item event, send this item to our server
_addItemSubject
.stream
.flatMap((input) => manager.addItem(input))
.listen(_addResponseSubject.add, error: (e) => handleError(e));
}
}
class EditBloc extends BaseBloc {
// Sink to receive the event to edit an item
var _editItemSubject = PublishSubject<Input>();
Sink<Input> get editItemSink => _editItemSubject.sink;
// Stream with the response from the server, the edited item
var _editResponseSubject = PublishSubject<Item>();
Stream<Item> get editResponseStream => _editResponseSubject.stream;
AddBloc(ItemsManager manager) {
// When we receive the edit item event, send the edited item to our server
_editItemSubject
.stream
.flatMap((input) => manager.editItem(input))
.listen(_editResponseSubject.add, error: (e) => handleError(e));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment