Esito ambition is to be your return type for suspending functions.

Overview

Esito

Esito ambition is to be your return type for suspending functions.

Installation

repositories {
	maven { url 'https://jitpack.io' }
}

dependencies {
    implementation("com.github.Subito-it.Esito:core:(insert latest version)")
}

Getting started

The main class is the sealed class Result, with two subtypes:

  • Success: it contains the result of a successful computation
  • Failure: it contains the cause of an unsuccessful computation

The goal when using Esito is to avoid throwing exceptions and use Result as the return type of a function that can fail:

sealed class ConversionError
object EmptyInput : ConversionError()
object NotNumericInput : ConversionError()

fun fromStringToInt(input: String): Result<Int, ConversionError> = when {
    input.isBlank() -> Result.failure(EmptyInput)
    else -> runCatching { input.toInt() }.mapError { NotNumericInput }
}

In this example we are defining all the possible failures in ConversionError, then we are applying some logic to build our result.

If the input is not blank we are using the runCatching method to wrap a method throwing an exception and mapping the eventual error in our desired type.

Operators

Esito result has several operators, such as map and flatmap, for examples see Recipes.

Retrofit Integration

Esito ships an integration with retrofit, after a one-line setup you can start to use Result return type in your Retrofit interfaces:

, Throwable> } ">
interface GitHubService {
    
    @GET("users/{user}/repos")
    fun listRepos(@Path("user") user: String?): Result<List<Repo>, Throwable>
}

For additional info and to learn how to use your own Error instead of Throwable have a look at this documentation.

Async Utilities

Esito offers some utilities for suspending methods returning Result. For example, suppose we have the following functions:

suspend fun getUserFullName(userId: Int): Result<String, FeatureError>

suspend fun getUserStatus(userId: Int): Result<UserStatus, FeatureError>

And we have to return an instance of DataForUI running in parallel getUserFullName and getUserStatus.

data class DataForUI(
	val userFullName: String,
	val userStatus: UserStatus
)

Esito exposes a zip method to compute two independent execution in parallel:

suspend fun fetchIfo(userId: Int): Result<DataForUI, FeatureError> =
	zip(
		{ getUserFullName(userId) },
		{ getUserStatus(userId) },
		::DataForUI //syntactic sugar for constructor
		).invoke()

For additional info have a look at this documentation.

Testing

Esito is providing two extension methods to facilitate testing: assertIsSuccess and assertIsFailure, here is an example of usage:

val success = Result.success<Int, Throwable>(42)
success.assertIsSuccess {
    assertEquals(42, value)
}

val failure = Result.failure<Int, RuntimeException>(RuntimeException("Ops"))
failure.assertIsFailure {
    assertEquals("Ops", error.message)
}

For additional info have a look at this documentation.

You might also like...
An annotation processor library that automatically creates Hilt's `@Binds` functions and modules.
An annotation processor library that automatically creates Hilt's `@Binds` functions and modules.

HiltBinder An annotation processor library that automatically creates Hilt's @Binds functions and modules. If you think this library is useful, please

A ksp library to automatically generate navigation functions for jetpack compose.
A ksp library to automatically generate navigation functions for jetpack compose.

Compose/Navigation/Generator ⚠️ This library is still under development and not considered stable! Content Introduction Usage Example: Single destinat

🧮 Provides simple and advanced mathematical functions in a beautifully designed UI.
🧮 Provides simple and advanced mathematical functions in a beautifully designed UI.

Calculator 🧮 Android App 🔗 Download the App 🤔 What is this App ✍️ This will basically provide simple and advanced mathematical functions in a beaut

Easy app for managing your files without ads, respecting your privacy & security
Easy app for managing your files without ads, respecting your privacy & security

Simple File Manager Can also be used for browsing root files and SD card content. You can easily rename, copy, move, delete and share anything you wis

To help to promote your android app by prompting users to rate your app in a bottom Sheet.

RateBottomSheet This an Android library to help to promote your Android App by prompting users to rate your app in the Google Play Store with a materi

TakeNotes, taking care of your tasks and your health
TakeNotes, taking care of your tasks and your health

Take Notes - Para tornar sua rotina mais Saudável TakeNotes, cuidando de suas tarefas e de sua saúde Sobre • Funcionalidades • Layout • Como executar

Binding your extras more easier, more simpler for your Android project

Ktan Ktan make your intent / arguments more easier and readable. And most important, will help you bind all extras for your activity / fragment. And a

Simple view which allow you to customise your pizza's toppings and size as per your choice.
Simple view which allow you to customise your pizza's toppings and size as per your choice.

TwistedPizzaToppingsView Overview Simple view which allows options to customize your pizza toppings and size as per your choice. Features Android 12 s

Browse your memories without any interruptions with this photo and video gallery
Browse your memories without any interruptions with this photo and video gallery

Simple Gallery Simple Gallery Pro is a highly customizable lightweight gallery loved by millions of people for its great user experience. Organize and

Comments
  • Retrofit responses with a null body

    Retrofit responses with a null body

    Currently, when using Esito's Result with a network request that returns a null body (example: fun foo(...): Result<Unit, Throwable>), EsitoBodyThrowableCall crashes because it tries to get a non-null body:

    private fun <T> Response<T>.toEsitoResult(): Result<T, Throwable> {
            return if (isSuccessful) {
                Result.success(body()!!)
            } else {
                Result.failure(HttpException(this))
            }
        }
    
    opened by MovementSpeed 0
Owner
null
Portfolio application for the purpose of listing events according to the return of an API

My Event Schedule Aplicativo portifólio com a finalidade de listar eventos de ac

Ricardo Souza 2 Feb 26, 2022
Praveen Kumar Kumaresan 0 Jan 17, 2022
Bring type-safety to your GitHub actions' API!

GitHub Actions typing Bring type-safety to your GitHub actions' API! This is a GitHub action that validates your action's type specs (action-types.y(a

Piotr Krzemiński 23 Dec 18, 2022
Firestore Kotlin Client with strict (and relaxed) type-system.

Firestore Kotlin Client with strict (and relaxed) type-system.

Vihang Patil 2 Mar 4, 2022
The sample App implements type safe SQL by JOOQ & DB version control by Flyway

The sample App implements type safe SQL by JOOQ & DB version control by Flyway Setup DB(PostgreSQL) $ docker compose up -d Migration $ ./gradlew flywa

t-kurihara 3 Jan 1, 2022
Lambë Language 7 Dec 21, 2022
Kotlin extension function provides a facility to "add" methods to class without inheriting a class or using any type of design pattern

What is Kotlin Extension Function ? Kotlin extension function provides a facility to "add" methods to class without inheriting a class or using any ty

mohsen 21 Dec 3, 2022
The WeeBe application is a social media-type app built on Ktor framework

The WeeBe application is a social media-type app built on Ktor framework that allows users to exchange various content connected with mental health, motivation, psychology, and improving oneself. Users can share posts with texts, images, videos, and links, as well as discuss the content in the comment section

Perpetio 3 Aug 5, 2022
Kotlin extensions, BindingAdapters, Composable functions for Android CameraX

Setup dependencies { implementation "com.github.skgmn:cameraxx:0.6.0" } Features CameraXX provides extensions methods for CameraX to use functions

null 12 Aug 9, 2022
Helper functions for making Approvals-Java more Kotlin friendly

Approvals-Kt Helper functions for making Approvals-Java more Kotlin-friendly Usage Verify using Approvals-Kt import com.github.greghynds.approvals.Kot

Greg Hynds 2 Oct 18, 2021