Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does FirstAsync work?

In my everlasting quest to suck less I'm trying to understand Rx.net's FirstAsync() syntax. Most documentation is for the deprecated First()
If I understand correctly it allows me to start a stream as soon as the first element from a stream arrives.

Say I have a stream myStream and I want to start a stream that takes the first element and starts a stream based on that one element. In my case it would be a stream of one.
I expect it to do this:

---1-2->
---A--->

How would I go about this?

myStream.FirstAsync().Return(() => return "A"); // doesn't compile
like image 898
Boris Callens Avatar asked Jun 10 '17 21:06

Boris Callens


1 Answers

I don't know why the other two answers are saying .FirstAsync() returns a Task (or that you should call .Result). It does not return a Task, it returns an IObservable<TSource>. Observables are awaitable, but they are not tasks.

To achieve your desired functionality, do the following: myStream.FirstAsync().Select(_ => "A").

You can also do myStream.Take(1).Select(_ => "A"). The difference between this and the FirstAsync version, is that the FirstAsync version will throw an exception if myStream completes without any elements. Take(1) will complete with no error.

like image 163
Shlomo Avatar answered Oct 10 '22 03:10

Shlomo