Flutter: Bloc dispose without waiting for the server response

458

Using the controller's isClosed property, you could just check if the controller is closed before adding the events, like so:

try {
  List answer = await call();
  if (!createList.isClosed) {
    createList.sink.add(answer);
  }
} on Exception catch(e) {
  if (!createList.isClosed) {
    createList.sink.addError(e);
  }
}
Share:
458
Little Monkey
Author by

Little Monkey

I'm just a little monkey!

Updated on December 08, 2022

Comments

  • Little Monkey
    Little Monkey over 1 year

    As soon as the user enters in a page, a call to the server will be executed. If the snapshot has data, a stream will be send to the UI with which will create a ListView, otherwise, if the snapshot has an error, a stream error message will be sinked.

    So, the call I have:

    try {
          List answer = await call();
          createList.sink.add(answer);
        } on Exception catch (e) {
          createList.sink.addError(e);
        }
    

    The problem is: if the connection is slow, and the user quits that page before the call is completed, the controllers will be disposed and the app will complain that the error cannot be sinked after that I've disposed the controller. So, is there a way to "abort" the call to the server when the user quits the page?

  • Little Monkey
    Little Monkey over 5 years
    I think you put a "sink" more. I just do "!createList.isClosed"