mirror of
https://github.com/bitwarden/android.git
synced 2024-12-18 07:11:51 +03:00
Add flatMap for Result type (#51)
This commit is contained in:
parent
70ec944469
commit
36942ab296
2 changed files with 62 additions and 0 deletions
|
@ -0,0 +1,10 @@
|
|||
package com.x8bit.bitwarden.data.platform.util
|
||||
|
||||
/**
|
||||
* Flat maps a successful [Result] with the given [transform] to another [Result], and leaves
|
||||
* failures untouched.
|
||||
*/
|
||||
inline fun <T, R> Result<T>.flatMap(transform: (T) -> Result<R>): Result<R> =
|
||||
this.exceptionOrNull()
|
||||
?.let { Result.failure(it) }
|
||||
?: transform(this.getOrThrow())
|
|
@ -0,0 +1,52 @@
|
|||
package com.x8bit.bitwarden.data.platform.util
|
||||
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class ResultTest {
|
||||
|
||||
@Test
|
||||
fun `flatMap where receiver is success and argument is success should be argument success`() {
|
||||
val intResult = Result.success(1)
|
||||
val stringResult = intResult.flatMap {
|
||||
Result.success(it.toString())
|
||||
}
|
||||
assertTrue(stringResult.isSuccess)
|
||||
assertEquals("1", stringResult.getOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `flatMap where receiver is success and argument is failure should be argument failure`() {
|
||||
val expectedException = IllegalStateException("Exception in transform")
|
||||
val intResult = Result.success(1)
|
||||
val stringResult = intResult.flatMap {
|
||||
Result.failure<String>(expectedException)
|
||||
}
|
||||
assertTrue(stringResult.isFailure)
|
||||
assertEquals(expectedException, stringResult.exceptionOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
@Suppress("TooGenericExceptionThrown")
|
||||
fun `flatMap where receiver is failure and argument is failure should be receiver failure`() {
|
||||
val expectedException = RuntimeException("Exception on int result.")
|
||||
val intResult = Result.failure<Int>(expectedException)
|
||||
val stringResult = intResult.flatMap<Int, String> {
|
||||
throw RuntimeException("transform function should not be called for failed Results")
|
||||
}
|
||||
assertTrue(stringResult.isFailure)
|
||||
assertEquals(expectedException, stringResult.exceptionOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `flatMap where receiver is failure and argument is success should be receiver failure`() {
|
||||
val expectedException = RuntimeException("Exception on int result.")
|
||||
val intResult = Result.failure<Int>(expectedException)
|
||||
val stringResult = intResult.flatMap {
|
||||
Result.success("1")
|
||||
}
|
||||
assertTrue(stringResult.isFailure)
|
||||
assertEquals(expectedException, stringResult.exceptionOrNull())
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue