0

Is there any way in Flutter to make an exception thrown in one method stop the execution of an unrelated method (i.e. a method that did not invoke the throwing method)?

It's a bit difficult to explain what I mean, but something like this:

void tryConnectDevice(Device device){
  await device.connect();
  await device.init();
}


/// This method can be called at any time from an external source, and
/// if `tryConnectDevice` is currently being executed it should be stopped 
/// immediately (i.e. by triggering an exception so that it doesn't 
/// wait for `connect()` or `init()` to finish).
void onDeviceDetached(){
  throw Exception('Device detached, stop tryConnectDevice()');
}

I tried experimenting with zones, but nothing so far has worked. Of course I could set some error flag somewhere and check that repeatedly in Device.connect() and Device.init() and throw if the flag is set, but I would very much prefer if there was a way to throw an exception from onDeviceDetached instead, so that the execution of Device.connect() or Device.init() receives that exception and throws, in turn making tryConnectDevice() throw...

Otherwise, what would be the best way to tackle something like this?

Magnus
  • 17,157
  • 19
  • 104
  • 189
  • You'd need to expose another method, e.g. `device.cancel()` that took some action. For example, let's say the device was talking over a socket and connect established the socket and init performed a handshake. In this case, device.cancel would close the socket causing connect and init to fail and handle the error of a prematurely closed socket however they normally did that (presumably by returning or throwing) – Richard Heap Aug 30 '23 at 16:12

0 Answers0