result-of
result-of copied to clipboard
A Kotlin utility sealed class for handling failure & success.
A utility sealed class for handling failure & success.
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 tomavenCentral()soon. However, if you removedjcenter()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
mapMap successful value into something elseflatMapMap anotherResultOf<T>into antherResultOf<R>failureMapMap throwable of the Failure into another throwable. For example, mapIllegalStateExceptiontoMyExceptionfailureFlatMapsame asflatMapbut for Failure
Retrieving Value & Throwable
result.valueOrNullresult.valueOrThrowresult.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