Skip to content

A Kotlin utility sealed class for handling failure & success.

License

Notifications You must be signed in to change notification settings

seanghay/result-of

Repository files navigation

A utility sealed class for handling failure & success.

Build License

This is not the same as standard Kotlin Result because it is a sealed class not a value class (previously called inline class).

Installation

dependencies {
    implementation("com.seanghay:resultof:1.0.0")
}

⚠️ The library is still in jcenter(), I plan to move it to mavenCentral() soon. However, if you removed jcenter() from your repositories, it will not be resolved. I suggest use jitpack for the time being.

JitPack

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

dependencies {
    implementation 'com.github.seanghay:result-of:1.0.0'
}

Basic Usage

val result = resultOf {
    fetchUsers()
}

result.onSuccess { users -> println(users) }
result.onFailure { throwable -> println(throwable) }

Usage with LiveData

class MyViewModel : ViewModel() {
    val profile = liveData {
        val result = resultOf { userRepository.getMyProfile() }
        emit(result)
    }
}
class MyFragment: Fragment() {
    
    private val viewModel: MyViewModel by viewModels()
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    
        // observe user profile result
        viewModel.profile.observe(viewLifecycleOwner) { result -> 
            
            // we only need `profileUrl` so we map it.
            result.map { it.profileUrl }.onSuccess { url ->
                Glide.with(this)
                    .load(url)
                    .into(binding.imageView)
            }

            result.onFailure { throwable -> 
                Toast.makeText(
                    requireContext(), 
                    throwable?.localizedMessage ?: "Oops!", 
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }
}

Transformations

  • map Map successful value into something else
  • flatMap Map another ResultOf<T> into anther ResultOf<R>
  • failureMap Map throwable of the Failure into another throwable. For example, map IllegalStateException to MyException
  • failureFlatMap same as flatMap but for Failure

Retrieving Value & Throwable

  • result.valueOrNull
  • result.valueOrThrow
  • result.valueOrDefault { "my-default-value" }
  • result.throwableOrNull

Conversion

We can convert from standard Kotlin Result into ResultOf by calling asResultOf() on Result object.

val result = runCatching { 12345 }.asResultOf()

Nullable ResultOf to Non-null ResultOf Conversion

Most of the time, we don't want null value to be the successful value, so we want it to be a Failure instead. We can do that by calling failureOnNull()

val nullableResult: ResultOf<String?> = resultOf { null }
val nonNullResult: ResultOf<String> = nullableResult.failureOnNull()

println(nullableResult.isFailure)
// false

println(nonNullResult.isFailure)
// true

About

A Kotlin utility sealed class for handling failure & success.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages