-
Notifications
You must be signed in to change notification settings - Fork 1.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add first { … } terminal operator to Flow #1078
Comments
You throw |
and |
Add some use-case, please |
I made a library to return scan results from the Bluetooth Low Energy API of Android, and often, the use case is to scan for all devices, or devices responding to a filter list passed to the system, to find one device, the one you want, which effectively, is the first one, or the first one matching a predicate. I currently do this using a I would like to try to use Here's the relevant lines of code for the channel based API: https://github.com/Beepiz/BleScanCoroutines/blob/5904bc44089e722145f987d653f1c77f479b9af2/core/src/main/java/com/beepiz/bluetooth/scancoroutines/experimental/BluetoothLeScanner.kt#L18-L29 |
I'm not used to reactive streams at all though. Maybe @JakeWharton or others can bring some use cases, or tell if that doesn't make sense or is a recipe for undesirable use of reactive streams. |
Not sure I've used it much except for in tests. If you're doing something with a nested stream (like |
I have a function where I need to fetch the next new element receied from a ConflatedBroadcastChannel. So I use private object NullSurrogate
private object FirstException : CancellationException("First received")
suspend fun <T> Flow<T>.first(): T {
var result: Any? = NullSurrogate
try {
collect { value ->
result = value
throw FirstException
}
} catch (ignored: FirstException) {
}
if (result === NullSurrogate) {
throw NoSuchElementException("Expected at least one element")
}
@Suppress("UNCHECKED_CAST")
return result as T
} Would this be a good implementation of |
@PaulWoitaschek You're talking about |
Instead of openSubscription I call asFlow().drop(1).first() |
My use case is that I needed to observe a
|
Any reason |
Would be much like
first { … }
fromkotlin.collections
, collecting all elements until the predicate returns true, after which it would cancel the flow.I'm not sure what the behavior should be when the flow is empty though.
The text was updated successfully, but these errors were encountered: