RX Subjects - are they to be avoided?

后端 未结 4 1296
攒了一身酷
攒了一身酷 2020-12-15 05:06

I\'ve had a mini-discussion on the topic in another thread, and would like to have people\'s input on the \"bad\" sides of subjects.

People who frequent the RX forum

相关标签:
4条回答
  • 2020-12-15 05:08

    Seems like a lot of commenters are talking past each other.

    Last time I used a Subject was when I needed to pass a delegate to a middleware in an initialisation call so it could call me back when something happened. The delegate had the familiar event args signature, but I couldn't use FromEvent because there was no event.

    I didn't feel bad about it - I didn't see any other choice.

    Basically I used Subjects only when I'm originating some event and putting it into the Rx world, or when I need a handle to some future subscriber that hasn't arrived yet. Subjects let me link what I've got now to a later subscriber.

    0 讨论(0)
  • 2020-12-15 05:09

    I use Subject/Publish whenever reactive combinators are being duplicated due to lazy eval.

    However, for casual use I feel Subjects are a bit heavy - OnNext might be potential bottle neck - shows up as a hotspot during profiling, perhaps because of concurrency checks while pushing a value to subscribers.

    I feel it's also cleaner for Observables you know are hot by definition.

    0 讨论(0)
  • 2020-12-15 05:13

    Erik Meijer is thinking in a purely functional way - Subjects are the mutable variables of Rx. So, in general usage he's right - using Subjects is sometimes a way to cop out of Thinking Functionally, and if you use them too much, you're trying to row upstream.

    However! Subject are extremely useful when you're interfacing with the non-Functional world of .NET. Wrapping an event or callback method? Subjects are great for that. Trying to put an Rx "interface" onto some existing code? Use a Subject!

    0 讨论(0)
  • 2020-12-15 05:25

    One reason that I would be wary of using a Subject<T> as a part of the public API is that it mixes concerns; an observer is a concern distinct from the observable.

    What if some miscreant observer calls OnNext or OnCompleted or OnError on the Subject<T> where it was only supposed to be an observer?

    Even if it isn't a part of the API, and you tuck it away in your server as a private backing field, just the very fact that it has a dual role is disturbing. In the case of using it as a backing field, you are still only expecting it to perform one role / concern -- that of an observable. However, it has the potential to do two things and that's just mentally disturbing.

    0 讨论(0)
提交回复
热议问题