resource_result 0.0.3
resource_result: ^0.0.3 copied to clipboard
A package that provides a Resource class of any type. Supports the states Success, Failure and Loading.
Provides a Resource class containing data of any type and an error of any type. This allows methods
to return a Resource<T> which can be a Success, Loading or Failure instead of returning
a T and throwing an Exception if the method fails. Additionally, if a method returns a Future
or Stream the Loading state can initially be returned.
Usage #
To return a resource from a method: #
Synchronous
Resource<int, String> parseInt(String value) {
try {
return Success(int.parse(value));
} catch (e) {
return Failure("Failed to parse value '$value'");
}
}
Asynchronous
Stream<Resource<OtherClass, String>> convert(Stream<SomeClass> toConvert) async* {
yield Loading(EmptyOtherClass());
await for (final someObject in toConvert) {
try {
final OtherClass converted = convertToSomeObject(someObject);
yield Success(converted);
} catch (e) {
yield Failure("Failed convert '$someObject'");
}
}
}
Use Resource result #
final Resource<int, String> result = parseInt("13");if (
result.hasData) {
Text("Parsed int successfully: ${result.data}");
} else {
Text("Failed to parse int: ${result.error}");
}
//or
convert
(
someStream).
listen
((resource) {
resource.resolve(
onSuccess: (someClassData) => Text(
"Converted someClass to otherClass instance successfully: $someClassData"),
onLoading: (_) => Text("Loading..."),
onFailure: (error) => Text("Failed to convert: $error"));
});