This is not the same as standard Kotlin Result
because it is a sealed class not a value class
(previously called inline class
).
dependencies {
implementation("com.seanghay:resultof:1.0.0")
}
⚠️ The library is still injcenter()
, 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.
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.seanghay:result-of:1.0.0'
}
val result = resultOf {
fetchUsers()
}
result.onSuccess { users -> println(users) }
result.onFailure { throwable -> println(throwable) }
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()
}
}
}
}
map
Map successful value into something elseflatMap
Map anotherResultOf<T>
into antherResultOf<R>
failureMap
Map throwable of the Failure into another throwable. For example, mapIllegalStateException
toMyException
failureFlatMap
same asflatMap
but for Failure
result.valueOrNull
result.valueOrThrow
result.valueOrDefault { "my-default-value" }
result.throwableOrNull
We can convert from standard Kotlin Result into ResultOf by calling asResultOf()
on Result object.
val result = runCatching { 12345 }.asResultOf()
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