Adrian Garza
Adrian Garza

Reputation: 195

Flutter freezed, when using union/sealed classes how to return a value and stop execution of function

I have this method, and I´m using the freezed flutter package to handle the network state.

I want to stop the execution of an async method in case I get a failure response using a union/sealed class.

 void wantedToStopExecutionInAsync() async {
    var resultFromNetworkCall = await myNetworkCall();

    resultFromNetworkCall.when(
      success: (value) {
        //do some work;
      },
      failure: (exception) {
        print(exeption);
        //Here I want to stop the execution of async function wantedToStopExecutionInAsync()
        return;
      }
    );

    //If result is a failure, I dont want to process the next line of code
    someOtherWork();
  }

I would like to stop execution when a failure response is received, is it possible?

An option would be

 void wantedToStopExecutionInAsync() async {
    var resultFromNetworkCall = await myNetworkCall();

    resultFromNetworkCall.when(
      success: (value) {
        //do some work;
      },
      failure: (exception) {
        print(exeption);
        //Here I want to stop the execution of async function wantedToStopExecutionInAsync()
        return;
      }
    );

    if (resultFromNetworkCall is Failure) {
        return;
    }

    //If result is a failure, I dont want to process the next line of code
    someOtherWork();
  }

but it´s not nice. Any suggestions?

Upvotes: 3

Views: 1307

Answers (1)

Yayo Arellano
Yayo Arellano

Reputation: 3866

Is not that hard. In the union return a boolean result. Check the next code fragment:

void wantedToStopExecutionInAsync() async {
  var resultFromNetworkCall = await myNetworkCall();

  bool success = resultFromNetworkCall.when(
    success: (value) {
      return true;
    },
    failure: (exception) {
      print(exeption);
      return false; // NOTE: Return of false
    },
  );
  
  //Stop the execution of async function wantedToStopExecutionInAsync()
  if (success == false || resultFromNetworkCall is Failure) {
    return;
  }

  //If result is a failure, I dont want to process the next line of code
  someOtherWork();
}

Upvotes: 1

Related Questions