Skip to content

Instantly share code, notes, and snippets.

@lukaspili
Last active Nov 13, 2019
Embed
What would you like to do?
import 'package:x/presentation/presentation.dart';
import 'activities_actions.dart';
import 'activities_state.dart';
class ActivitiesBloc {
BlocController<ActivitiesState, Action> get controller => _core;
BlocCore<ActivitiesState, ActivitiesStateBuilder, Action> _core;
ActivitiesBloc() {
_core = BlocCore<ActivitiesState, ActivitiesStateBuilder, Action>(
stateBuilderInitializer: _initializeStateBuilder,
stateInitializer: _initializeState,
dispatcher: _dispatch,
);
_core.subscribe<PaginatedList<Activity>>(
tag: 'activities',
initialValue: dependencies.resolve<ActivityInteractor>().currentActivities,
stream: dependencies.resolve<ActivityInteractor>().activities,
commit: (activities, _, builder) {
builder.activities = activities;
},
);
}
void dispose() {
_core.dispose();
}
ActivitiesStateBuilder _initializeStateBuilder() {
return ActivitiesStateBuilder()
..fetchTask = Task.idle
..toggleVisibilityTask = Task.idle;
}
void _dispatch(Action action) {
switch (action.runtimeType) {
case Refresh:
_onRefresh(action);
break;
case LoadMore:
_onLoadMore();
break;
case ToggleDiscoverable:
_onToggleOnline(action);
break;
case ShowDetails:
_onShowDetails(action);
break;
default:
assert(false);
}
}
void _onRefresh(Refresh action) {
if (_core.currentState.activities.currentPage > 1 && !action.isManual) {
return;
}
_fetch(page: 1);
}
void _onLoadMore() {
if (!_core.currentState.activities.canLoadMore) {
return;
}
_fetch(page: _core.currentState.activities.nextPage);
}
void _onToggleOnline(ToggleDiscoverable action) {
_core.subscribe<Task>(
tag: 'patchVisibility',
overrideSubscription: true,
stream: dependencies.resolve<SessionProviderInteractor>().patchVisibility(action.value),
commit: (task, _, builder) {
builder.toggleVisibilityTask = task;
},
);
}
void _onShowDetails(ShowDetails action) {
_core.navigate(Navigation(destination: Destination.activityDetails, payload: action.activity));
}
void _fetch({@required int page}) {
if (_core.currentState.fetchTask.isRunning) {
return;
}
_core.subscribe<Task>(
tag: 'fetch',
overrideSubscription: true,
stream: dependencies.resolve<ActivityInteractor>().fetch(page: page),
commit: (task, _, builder) {
builder.fetchTask = task;
},
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment