Skip to main content

Executors

A very common pattern in an asynchronous request is:


  @override  Future<void> fetchData(){    setLoading(true);    try {      final result = await repository.fetch();      update(result);    } catch(e){      setError(e);    }    setLoading(false);  }

You can use the execute method** and pass on Future to perform the same steps described in the previous example:


  @override  Future<void> fetchData(){   execute(() => repository.fetch());  }

The executors work like a switchMap, that is, if called again, the previous execution will be canceled. It is also possible to set a debounce time.

Execute Either (EitherAdapter)#

For users using dartz using Clean Architecture for example, they can also run the Either class using the executeEither method:

Step 1 - Create Adapter:#

class CustomEitherAdapter implements EitherAdapter {}

Step 2 - Add Left and Right type:#

class CustomEitherAdapter implements EitherAdapter<Exception, String> {}

Step 3 - Implement fold method (Using dartz or any other functional package):#

class DartzEitherAdapter implements EitherAdapter<Exception, String> {
  // receive an usecase in constructor  final Either<Exception, String> usecase;  DartzEitherAdapter(this.usecase);
  @override  T fold(T Function(Exception l) leftF, T Function(String r) rightF) {    return usecase.fold(leftF, rightF);  }
  // Adapter Future Either(Dartz) to Future EitherAdapter(Triple)  static Future<EitherAdapter<L, R>> adapter<L, R>(Future<Either<L, R>> usecase) {    return usecase.then((value) => DartzEitherAdapter(value));  }
}

Step 4 - Just use:#

 @override  Future<void> fetchData(){   executeEither(() => DartzEitherAdapter.adapter(myUsecase()));  }