Why are Subjects not recommended in .NET Reactive Extensions?

后端 未结 5 1678

I am currently getting to grips with the Reactive Extensions framework for .NET and I am working my way through the various introduction resources I\'ve found (mainly http:/

5条回答
  •  感动是毒
    2020-11-28 01:38

    In general you should avoid using Subject, however for the thing you are doing here I think they work quite well. I asked a similar question when I came across the "avoid subjects" message in Rx tutorials.

    To quote Dave Sexton (of Rxx)

    "Subjects are the stateful components of Rx. They are useful for when you need to create an event-like observable as a field or a local variable."

    I tend to use them as the entry point into Rx. So if I have some code that needs to say 'something happened' (like you have), I would use a Subject and call OnNext. Then expose that as an IObservable for others to subscribe to (you can use AsObservable() on your subject to make sure nobody can cast to a Subject and mess things up).

    You could also achieve this with a .NET event and use FromEventPattern, but if I'm only going to turn the event into an IObservable anyway, I don't see the benefit of having an event instead of a Subject (which might mean I'm missing something here)

    However, what you should avoid quite strongly is subscribing to an IObservable with a Subject, i.e. don't pass a Subject into the IObservable.Subscribe method.

提交回复
热议问题