none
What is the purpose of AsObservable and when should it be used? RRS feed

  • Question

  •     Subject<string> statusChanges = new Subject<string>();
    
        public IObservable<string> StatusChanges
        {
          get { return statusChanges.AsObservable(); }
        }

    I have seen the use of AsObservable() used with subjects but the code above will work without AsObserable() because we are returning IObservable from the property, so my question is what is the purpose of calling it in the case above and should one? When should it be used and when should it not be used? Internally AsObservable() is returning an AnonymousObservable object, which seems to do a lot more than simply subscribe to its source. Anyone got any thoughts on this.

    Friday, June 4, 2010 5:15 PM

Answers

  • Hi,

    The purpose of AsObservable in this case is to hide internal implementation details.  If you were instead to return statusChanges directly, then any consumer could cast the return value from IObservable<string> to Subject<string> and call OnNext, OnError or OnCompleted, clearly breaking encapsulation.

    Another usage of both AsObservable and AsEnumerable is to change the monad from IQbservable to IObservable and IQueryable to IEnumerable, respectively, within a single query.

    - Dave


    http://davesexton.com/blog
    • Edited by Dave Sexton Friday, June 4, 2010 5:28 PM Removed incorrect comment about AsEnumerable
    • Marked as answer by head.in.the.box Saturday, June 5, 2010 2:42 AM
    Friday, June 4, 2010 5:23 PM