Creating a hot observable and adding things to it

91 Views Asked by At

I am trying to create a hot observable where I can add stuff to it. Here's an outline of the basic class

public class MyObservable
{
    public IObservable<string> Stream;

    public MyObservable()
    {
         Observable.Create...?
    }

    public void AddString(string eventDescription)
    {
       //Add to Stream
    }
}

Somewhere else in the code I want to be able to do something like

var ob = new MyObservable();
MyObservable.Add("User created");

Then somewhere else something like:

ob.Stream.Subscribe(Console.WriteLine);

I am not really sure how I am supposed to add strings to the observable

edit: I've tried doing something like this, but I'm not sure if maybe I'm not doing things in the way it's supposed to be done

    private IObserver<string> _observer;

    public void Add(string e)
    {
        if(Stream == null) 
        { 
            Stream = Observable.Create<string>(
                (IObserver<string> observer) =>
                {
                    _observer = observer;
                    observer.OnNext(e);
                    return Disposable.Empty;
                });
        }
        else
        {
              _observer.OnNext(e);
        } 

    }
1

There are 1 best solutions below

3
On BEST ANSWER

You should do a little more reading on the contracts of observables and observers

Regardless, what you are looking for is a Subject, which implements both the Observable and Observer interfaces.

If you still want to wrap it it would look like so:

public class MyObservable
{
  private Subject<string> subject; 
  public IObservable<string> Stream 
  { 
    get { return this.subject.AsObservable();

  }

  public MyObservable()
  {
    subject = new Subject<string>();
  }

  public void AddString(string eventDescription)
  {
    //Add to Stream
    this.subject.OnNext(eventDescription);
  }
}