-
Notifications
You must be signed in to change notification settings - Fork 50
Conversation
By analogy to IterableExtensions.firstOrNull in the collection package.
I think we need to hold off on this until we have resolved dart-lang/core#330, and then we can put this in that library. In the short term we could add this in |
Co-authored-by: Nate Bosch <nbosch@google.com>
I don't think this would make sense in |
That's a good point. @lrhn - which library would you prefer this goes into? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I see no problem with adding it to StreamExtensions
in package:async
. It's the perfect place. The corresponding collection method was in package:collection
, so the analogy is perfect.
Code looks fine too.
We could consider adding more extensions along with this, perhaps before releasing 2.9.0, but starting here seems fine.
/// or `null` if it emits a done event first. | ||
Future<T?> get firstOrNull { | ||
var completer = Completer<T?>.sync(); | ||
final subscription = listen(null); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can use cancelOnError: true
. Then you can just tear off completer.completeError
instead of creating a new closure. It can even be:
var subscription = listen(null,
onError: completer.completeError,
onDone: completer.complete, // The argument is optional if the type is nullable!
cancelOnError: true);
subscription.onData((event) {
subscription.cancel();
completer.complete(event);
});
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I considered doing it that way, but I think the symmetry between the onData
and onError
events is easier to follow than having one of them manually cancel the subscription and the other cancel it through cancelOnError
.
By analogy to IterableExtensions.firstOrNull in the collection package.
By analogy to IterableExtensions.firstOrNull in the collection package.