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?