Reputation: 33379
So if I'm writing an extension method for a type in another library that converts that type into an Rx IObservable<T>
, what exactly is the convention? I ask because I thought AsObservable
was the way to go, but I've also seen ToObservable
. It's unclear to me which is used when or if there's any real convention at all.
Could it be ToObservable
is reserved for turning something that is expected to product a single event into an IObservable<T>
where as AsObservable
is reserved for converting something that is expected to produce a sequence of events into an IObervable<T>
?
Upvotes: 5
Views: 1499
Reputation: 18125
Unless you have a very good reason to write your own cross-duality operators, you will not need to write a "To" postfix when dealing with Enumerables and Observables.
Observe the following truths:
ToObservable
is expected to convert pull-based sequences into push-based sequences. ToEnumerable
is expected to convert push-based sequences into pull-based sequences.AsObservable
is expected to wrap a push-based type as IObservable< T >
. AsEnumerable
is expected to wrap a pull-based type as IEnumerable< T >
.Therefore, To
should be used when you're writing a method which switches the duality of the source, and As
should be used when the resulting duality is the same as the source's.
In most cases, you will be using As
for your own methods, because the cross-duality operators of ToObservable
and ToEnumerable
have already been written for you.
Sources: Personal experience, MSDN documentation (above), Erik Meijer himself.
Upvotes: 6
Reputation: 6155
I don't know of any official guidance, but the main metric I would use is to look at the amount of work you are doing. For most cases, there is a non-trivial amount of work being done (which is subjective in itself), such as turning an IEnumerable into an IObservable, and I would use ToObservable
. When the method does fairly trivial work, as with the Observable.AsObservable
extension method, AsObservable
seems the better choice. Another notable difference between these two methods is that AsObservable
is not much more than a type cast and doesn't make any real changes to behavior of the argument, but Observable.ToObservable(IEnumerable<T>)
returns an object with significantly different semantics.
Upvotes: 5