Created
November 20, 2024 06:56
-
-
Save gothedistance/88f82c08d1223ff52696bfef1a9474c4 to your computer and use it in GitHub Desktop.
Rust `andThen` implementation for Dart lang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// To Avoid Result callback hell manipulate Rust lang andThen method simple way. | |
sealed class Result<T> { | |
const Result(); | |
R match<R>({ | |
required R Function(Success<T> success) success, | |
required R Function(Failure<T> failure) failure, | |
}) { | |
if (this is Success<T>) return success(this as Success<T>); | |
if (this is Failure<T>) return failure(this as Failure<T>); | |
throw StateError('Unexpected type: $this'); | |
} | |
} | |
class Success<T> extends Result<T> { | |
final T value; | |
const Success(this.value); | |
} | |
class Failure<T> extends Result<T> { | |
final Object error; | |
const Failure(this.error); | |
} | |
class Auth { | |
final String token; | |
final String email; | |
final String userName; | |
Auth({required this.token, required this.email, required this.userName}); | |
} | |
Future<Result<Auth>> getUser(String email) async { | |
return Success(Auth(token: "aaa", email: email, userName: "aaa bbb")); | |
} | |
Future<Result<String>> login(String user) async { | |
if (user == "user123") { | |
return const Success("[email protected]"); | |
} | |
return Failure("Invalid user"); | |
} | |
extension ResultExtension<T> on Future<Result<T>> { | |
Future<Result<U>> andThen<U>(Future<Result<U>> Function(T) next) async { | |
final current = await this; | |
return current.match( | |
success: (s) => next(s.value), | |
failure: (f) => Future.value(Failure<U>(f.error)), | |
); | |
} | |
} | |
void main() async { | |
final result = await login("user123").andThen((user) => getUser(user)); | |
result.match( | |
success: (auth) => print("Success login for ${auth.value.userName}"), | |
failure: (err) => print("Login error: $err"), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment