Bloc: How to cancel a processing event in Flutter bloc?

Created on 20 Sep 2020  路  3Comments  路  Source: felangel/bloc

I have already implemented switchMap. However, I am curious about how can I cancel a processing Event A (OneTimeWebAppLauncherStarted below) once Event B (OneTimeWebAppLauncherCancelled) is dispatched. Basically, I am still seeing await callApi() is executed although the cancel event is dispatched before the execution of await callApi().

Code snippet of my bloc:

  @override
  Stream<ApiResponse<String>> mapEventToState(OneTimeWebAppLauncherEvent event) async* {
      if (event is OneTimeWebAppLauncherCancelled) {
        yield ApiResponse.notAsked();
      }

      if (event is OneTimeWebAppLauncherStarted) {
        yield ApiResponse.loading();
        data = await callApi();
        yield ApiResponse<String>.completed(data: data);
      }
  }


  @override
  Stream<Transition<Event, ApiResponse>>
      transformEvents(
          Stream<OneTimeWebAppLauncherEvent> events,
          TransitionFunction<OneTimeWebAppLauncherEvent, ApiResponse>
              transitionFn) {
    return events.switchMap(transitionFn);
  }
question

Most helpful comment

Thanks @felangel @RollyPeres !

All 3 comments

Hi @lzhuor 馃憢

If what you want is to cancel the API request then I'd suggest you use dio http client and make use of its CancelToken.

Alternatively, you could make use of async package with CancelableOperation or CancelableCompleter.

@lzhuor closing for now but feel free to comment with additional questions and I'm happy to continue the conversation 馃憤

Thanks @felangel @RollyPeres !

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tigranhov picture tigranhov  路  3Comments

hivesey picture hivesey  路  3Comments

abinvp picture abinvp  路  3Comments

rsnider19 picture rsnider19  路  3Comments

wheel1992 picture wheel1992  路  3Comments