Skip to content

A kotlin library to help represent and handle loading, success and error states in Kotlin.

License

Notifications You must be signed in to change notification settings

NeoUtils/Resource

Folders and files

NameName
Last commit message
Last commit date

Latest commit

9a39701 · Sep 24, 2023

History

34 Commits
Sep 24, 2023
Sep 22, 2023
Aug 17, 2023
Sep 24, 2023
Aug 17, 2023
Sep 24, 2023
Sep 24, 2023
Sep 24, 2023
Aug 17, 2023
Sep 23, 2023
Aug 17, 2023
Aug 17, 2023

Repository files navigation

Resource

Complete solution for handling success, failure, and loading states in Kotlin.

Loading

Use the sealed class Resource with loading states.

ordersRepository.flow.collect { resource ->
    when (resource) {
        is Resource.Result.Failure -> //...
        is Resource.Result.Success -> //...
        Resource.Loading -> //...
    }
}

Result

If the possible states are success and error, the ideal class is Resource.Result.

when (ordersRepository.getOrders()) {
    is Resource.Result.Failure -> //...
    is Resource.Result.Success -> //...
}

Extensions

The library comes with some basic extensions to handle and manipulate the states.

kotlin.Result

Integration with kotlin Result.

suspend fun getOrders(): Resource.Result<List<Order>, String> {
    val result = runCatching {
        service.getOrders()
    }.toResource()
    
    return result.mapError {
        it.message ?: ""
    }.ifFailure {
        logger.send("error: $it")
    }.ifSuccess {
        logger.send("success: $it")
    }
}

Releases

The latest release is available on JitPack.

Add the jitpack to project in root build.gradle.kts or settings.gradle.kts:

repositories { 
    maven { url = uri("https://jitpack.io") }
}

Add the dependence to module:

implementation("com.github.NeoUtils:Resource:{version}")

License

Copyright (c) 2023 Irineu A. Silva

This project is licensed under the terms of the MIT License, 
a permissive open-source license that allows for the use, modification, 
and distribution of the code, provided that copyright notices and 
the license statement are included in all copies or modifications.