Search code examples
flutterfunctiondartstate-managementcubit

How to cancel cubit old function call?


I am trying to use cubit in my flutter project but i am facing this problem i am trying to call a function its function with future return type so its need time to be done but at the same time i got a notify so i need to call another function in side this cubit but i want to cancel the previous function first how can i do this thanks for your help .

class ConnectionCheckerCubit extends Cubit<ConnectionCheckerState> {
  ConnectionCheckerCubit() : super(ConnectionCheckerInitial());

  void whenConnectedFunction() {
    print('test1');
  }

  void whenDisconnectedFunction() async {
    print('test2');
    await Future.delayed(Duration(seconds: 10));
    print('test3');
  }
}

i call the second function whenDisconnectedFunction its print test2 then i call the upper function whenConnectedFunction before the 10 seconds end its print test1 but its also test3 is printed how can i fix this problem . thx .


Solution

  • I find a good way to solve this problem you can use bloc with bloc_concurrency package, this package let you handle bloc event as you want, so if you set the event for restartable it will cancel the old event and start new one .