Gianpaolo
10/31/2023, 9:42 AMclass CustomError {
data class RetrofitError(val error: Throwable) : CustomError()
// Add other custom errors if needed
}
suspend fun getUser(): Either<CustomError, User> {
return try {
val response: Response<User> = retrofitApi.getUser()
if (response.isSuccessful) {
response.body()?.right() ?: CustomError.RetrofitError(Throwable("No user found")).left()
} else {
CustomError.RetrofitError(Throwable("Response not successful")).left()
}
} catch (e: Exception) {
CustomError.RetrofitError(e).left()
}
}
dave08
10/31/2023, 10:41 AMG Filippa
10/31/2023, 11:49 AMG Filippa
10/31/2023, 3:55 PMdave08
10/31/2023, 3:58 PMG Filippa
10/31/2023, 3:59 PMdave08
11/12/2023, 3:13 PMG Filippa
11/12/2023, 4:01 PMChantry Cargill
12/08/2023, 12:53 PMfun example() = Either.catch { ... }
2. Using the raise API you can unwrap eithers sort of akin to async await
fun example(): Either<String, String> = either {
val x = somethingReturningEither().bind()
val y = somethingElseWithDifferentLeft().mapLeft { "y failed" }.bind()
ensureNotNull(x) { "Missing my x!" }
x + y
}
G Filippa
12/12/2023, 8:40 AM