Last active
June 12, 2023 15:01
-
-
Save jfsanchez91/13201da3e72a862498b30ffde23472f1 to your computer and use it in GitHub Desktop.
Kotlin coroutines ext Flow operators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package util.ext | |
import kotlinx.coroutines.flow.Flow | |
import kotlinx.coroutines.flow.count | |
import kotlinx.coroutines.flow.first | |
suspend fun <T> Flow<T>.all(predicate: suspend (T) -> Boolean): Boolean { | |
return this.count { !predicate(it) } == 0 | |
} | |
suspend fun <T> Flow<T>.any(predicate: suspend (T) -> Boolean): Boolean { | |
try { | |
this.first { predicate(it) } | |
} catch (e: NoSuchElementException) { | |
return false | |
} | |
return true | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package util.ext | |
import kotlinx.coroutines.flow.asFlow | |
import kotlinx.coroutines.test.runTest | |
import org.junit.jupiter.api.Assertions | |
import org.junit.jupiter.api.Test | |
internal class FlowExtKtTest { | |
@Test | |
fun `Flow.all checks all elements match the predicate`() = runTest { | |
val items = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0).asFlow() | |
Assertions.assertTrue(items.all { it <= 10 }) | |
Assertions.assertFalse(items.all { it >= 4 }) | |
} | |
@Test | |
fun `Flow.any checks that at least one element matches the predicate`() = runTest { | |
val items = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0).asFlow() | |
Assertions.assertTrue(items.any { it <= 0 }) // '0' matches | |
Assertions.assertTrue(items.any { it >= 4 }) // '4, 5, 6, 7, 8, 9' match | |
Assertions.assertFalse(items.any { it < 0 }) // No matches | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment