Skip to content
This repository has been archived by the owner on Oct 17, 2024. It is now read-only.

Commit

Permalink
make it easy to get result value
Browse files Browse the repository at this point in the history
  • Loading branch information
HosamHasanRamadan committed Jul 2, 2024
1 parent c0d81f8 commit b0eb4f6
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/async.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export 'src/restartable_timer.dart';
export 'src/result/error.dart';
export 'src/result/future.dart';
export 'src/result/result.dart';
export 'src/result/result_extensions.dart';
export 'src/result/value.dart';
export 'src/single_subscription_transformer.dart';
export 'src/sink_base.dart';
Expand Down
16 changes: 16 additions & 0 deletions lib/src/result/result_extensions.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import 'result.dart';

extension ResultExtensions<T> on Result<T> {
/// Returns the value if the result [isValue].
///
/// If the result [isError], it throws the corresponding error and stacktrace.
T get requireValue {
if (isValue) return asValue!.value;
Error.throwWithStackTrace(asError!.error, asError!.stackTrace);
}

/// Returns the value if the result [isValue].
///
/// Returns null otherwise
T? get valueOrNull => asValue?.value;
}
67 changes: 67 additions & 0 deletions test/result/result_extensions_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import 'package:async/async.dart';
import 'package:test/test.dart';

void main() {
group('test requiredValue', () {
test(
'return value when result is value',
() {
final result = Result.value(10);
expect(result.requireValue, 10);
},
);

test(
'return nullable value when result is nullable value',
() {
final result = Result<int?>.value(null);
expect(result.requireValue, null);
},
);

test(
'throw exception when result is error',
() async {
final result = Result.error('error');
expect(() => result.requireValue, throwsA(anything));
},
);

test(
'throw the corresponding and stacktrace exception when result is error',
() async {
final error = Exception();
final stacktrace = StackTrace.current;
final result = Result.error(error,stacktrace);

expect(
() => result.requireValue,
throwsA(
predicate((err) {
return err == error;
}),
),
);
},
);
});

group('test valueOrNull', () {
test('return null when result is error', (){
final result = Result.error('error');
expect(result.valueOrNull, null);
});

test('return value when result is value ', (){
final result = Result.value(10);
expect(result.valueOrNull, 10);
});

test('return nullable value when result is nullable value ', (){
final result = Result<int?>.value(null);
expect(result.valueOrNull, null);
});

});

}

0 comments on commit b0eb4f6

Please sign in to comment.