When the app starts, I dispatch an action FetchLocalDataRequestAction
and intercept this action in a middleware and dispatch multiple actions. I want to dispatch FetchLocalDataCompleteAction
actions when all actions are completed. I was expecting that the dispatch function would return a Future
which I can wait and when all the Future
's are completed I could have dispatched the complete action.
I'm using redux_epics middleware for performing side effects using Streams
Middleware
fetchLocalData<State>(
Store<State> store,
action,
NextDispatcher next
){
if(action is FetchLocalDataRequestAction){
final futureLanguage = store.dispatch(FetchPreferredLanguageRequestAction());
print('futureLanguage : $futureLanguage '); // null
store.dispatch(FetchLocalUserRequestAction());
store.dispatch(FetchOnboardingStatusRequestAction());
}
next(action);
}
Epics
Stream fetchUserEpic(Stream actions, EpicStore<AppState> store) =>
actions.whereType<FetchLocalUserRequestAction>()
.debounceTime(Duration(seconds: 5))
.switchMap((action) => _fetchUser());
Stream _fetchUser() =>
handleException<AuthResponse, FetchLocalUserResultAction, FetchLocalUserErrorAction>(
api: () => _mergeUser(),
onResult: (result) => FetchLocalUserResultAction(result),
onError: (error) => FetchLocalUserErrorAction(error)
);
Future<AuthResponse> _mergeUser() async {
final token = await SharedPreferenceService.getAccessToken();
final user = await SharedPreferenceService.getUser();
return AuthResponse(token: token, user: user);
}
Stream fetchPreferredLanguageEpic(Stream actions, EpicStore<AppState> store) =>
actions.whereType<FetchPreferredLanguageRequestAction>()
.switchMap((action) => _fetchPreferredLanguage());
Stream _fetchPreferredLanguage() =>
handleException<String, FetchPreferredLanguageResultAction, FetchPreferredLanguageErrorAction>(
api: () => SharedPreferenceService.getLanguageCode(),
onResult: (code) => FetchPreferredLanguageResultAction(code),
onError: (error) => FetchPreferredLanguageErrorAction(error)
);
Stream fetchOnboardingStatusEpic(Stream actions, EpicStore<AppState> store) =>
actions.whereType<FetchOnboardingStatusRequestAction>()
.switchMap((action) => _fetchOnboardingStatus());
Stream _fetchOnboardingStatus() =>
handleException<OnboardingStatus, FetchOnboardingStatusResultAction, FetchOnboardingStatusErrorAction>(
api: () => SharedPreferenceService.getOnboardingStatus(),
onResult: (status) => FetchOnboardingStatusResultAction(status),
onError: (error) => FetchOnboardingStatusErrorAction(error)
);