SandroMaglione / fpdart

Functional programming in Dart and Flutter. All the main functional programming types and patterns fully documented, tested, and with examples.
https://pub.dev/packages/fpdart
MIT License
533 stars 44 forks source link

Add getOrThrow for Either TaskEither #115

Closed MiniSuperDev closed 1 year ago

MiniSuperDev commented 1 year ago

Hello, Just as there is an TaskEither.tryCatch, there may be scenarios where we want the opposite behavior (throw the left), like in your example with riverpod.

https://github.com/SandroMaglione/fpdart/blob/505c2250b7877b04ede2b2dce15b0c6f93f4cd02/examples/pokeapi_functional/lib/controllers/pokemon_provider.dart#L13 Would be:

  FutureOr<Pokemon> build() async =>
      fetchRandomPokemon.getOrThrow().run();

https://github.com/SandroMaglione/fpdart/blob/505c2250b7877b04ede2b2dce15b0c6f93f4cd02/examples/pokeapi_functional/lib/controllers/pokemon_provider.dart#L27-L30 Would be:

state = await AsyncValue.guard(()=> pokemon.getOrThrow().run());

or shorter

state = await AsyncValue.guard(pokemon.getOrThrow().run);
SandroMaglione commented 1 year ago

I would avoid adding a specific method to throw in fpdart core. The idea is to keep fpdart focused on functional error handling, without allowing throw directly inside types as Either. I think that having a "throw" method would make the core error handling methods less used, since most people would fallback to just throwing instead of properly handling errors.

My suggestion is to add an extension method on Either/TaskEither for your specific project if needed with a getOrThrow method.

Let me know if this works, feel free to continue the discussion below if needed.