简体   繁体   中英

How to create an Observable “channel” in Rx?

I started to transform my push -> pull bridge to a much simpler construct with Reactive Extensions.

So now I have a class with a (private) event, and an Observable created from it.

class WithEvents {
   public class MyEvent {}
   private delegate void MyEventHandler(MyEvent e);
   private event MyEventHandler EventRaised;

   Public IObservable<MyEvent> TheEvents;

   public void Foo() {
      EventRaised(new MyEvent());
   }

}

Thing is, this event seems like unneeded scaffolding here. So I was wondering: is there a way to construct a 'bare' Observable, that I can just 'push' events to?

class WithChannel {
    public class MyEvent {}
    public IObservable<MyEvent> EventRaised {get} = new Channel<MyEvent>();

    public void Foo() {
       ((Channel)EventRaised).DoNext(new MyEvent());
    }
}

Yes, there is a thing called Subject (in System.Reactive.Subjects namespace) which does exactly that:

class WithChannel {
    public class MyEvent {
    }

    private readonly Subject<MyEvent> _event;

    public WithChannel() {
        _event = new Subject<MyEvent>();
    }

    public IObservable<MyEvent> EventRaised => _event;

    public void Foo() {
        _event.OnNext(new MyEvent());
    }
}

Usage of subjects is generally not recommended, but for this specific task I think it's fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM