Is a Subject in RX.Net always harmful? subject tutorial
rx net examples
rx net operators
observable.create c#
c# reactive extensions performance
observable timer c#

I was talking to a colleague who pointed me to the SO question about subjects being considered harmful. However, I have two cases where I have some non-deterministic code that does not seem reasonable any other way.

Non-standard event:

 event handler(class, result)

 public delegate void _handler
   ([MarshalAs(UnmanagedType.Interface), In] MyClass class, 
    [MarshalAs(UnmanagedType.Interface), In] ResultClass result)

Parallel Tasks (Non-Deterministic number of tasks all running in parallel, starting at different times):

 Task.Start(()=> ...).ContinueWith(prevTask => subject.OnNext(prevTask.result))

The subject is not exposed, only through an observable. Is there another route suggested that isnt a ton of boilerplate?

Subjects are not always harmful. There are many legitimate uses of them even within Rx itself. However, many times a person goes to use a Subject, there's already a robust Rx method written for that scenario(and it may or may not be using subjects internally). This is the case for your 2 examples. Look at Task.ToObservable and Observable.FromEventPattern.

Another common case subjects are misused is when a developer breaks a stream in two. They become convinced they need to subscribe to a stream and in the callback they produce data for a new stream. They do this with a Subject. But usually they just should have used Select instead.

c# - Is a Subject in RX.Net always harmful?, Subjects are not always harmful. There are many legitimate uses of them even within Rx itself. However, many times a person goes to use a Subject, there's  To assess the adductor magnus, the subject would lie supine on a mat. The assessor would slowly move the bent knee toward the subject's arm pit (on the same side). The angle of the hip when the pelvis begins to posteriorly rotates should be noted as well any sensations the subject feels.


System.FromEvent works for more than just built-in event types: you just need to use the correct overload.

class Program
    private static event Action<int> MyEvent;

    public static void Main(string[] args)
            (handler) => Program.MyEvent += handler,
            (handler) => Program.MyEvent -= handler


Task.ToObservable & Merge

If you already have access to all of your tasks, you can convert them to Observables, and Merge them into a single observable.

class Program
    public static void Main(string[] args)
                // Async / Await
                    (async () => { await Task.Delay(250); return "async await"; })
                // FromResult
                // Run
                Task.Run(() => "Run").ToObservable()

Merge Observable

Alternatively, if you do not have all of your tasks up front, you can still use Merge, but you'll need some way of communicating future tasks. In this case, I've used a subject, but you should use the simplest Observable possible to express this. If that's a subject, then by all means, use a subject.

class Program
    public static void Main(string[] args)
        // We use a subject here since we don't have all of the tasks yet.
        var tasks = new Subject<Task<string>>();

        // Make up some tasks.
        var fromResult = Task.FromResult("FromResult");
        var run = Task.Run(() => "Run");
        Func<Task<string>> asyncAwait = async () => {
            await Task.Delay(250);
            return "async await";

        // Merge any future Tasks into an observable, and subscribe.

        // Send tasks.


Why to use or not to use Subjects is a question I don't have the time to answer adequately. Typically speaking, however, I find that using a Subject tends to be the "easy way out" when it appears an operator does not already exist.

If you can somehow limit the exposure of a subject in terms of it's visibility to the rest of the application, then by all means use a subject and do so. If you're looking for message bus functionality, however, you should rethink the design of the application, as message buses are anti-patterns.

To Use Subject Or Not To Use Subject?, [Subjects] are the "mutable variables" of the Rx world and in most cases you do not NET event and expose it as an observable public property using FromEventPattern! And keep in mind that you can always expose an event as an Note that it's bad practice to call Connect yourself in this scenario. Rx is also very well suited for introducing and managing concurrency for the purpose of offloading. That is, performing a given set of work concurrently to free up the current thread. A very popular use of this is maintaining a responsive UI. You should consider using Rx if you have an existing IEnumerable<T> that is attempting to model data

Subjects aren't harmful. That is probably even a little too dogmatic for me (and I am first to boo-boo the use of subjects). I would say that Subjects indicate a code smell. You probably could be doing it better without them, but if you keep the encapsulated within your class then at least you keep the smell in one place.

Here I would say, that you are already using "non-standard" event patterns, and it seems you don't want to, or cant, change that. In this case, it seems the usage of subjects as a bridge isn't going to make it any worse than it is.

If you were starting from scratch, then I would suggest that you deeply think about your design and you will probably find that you just wouldn't need a subject.

Lastly, I agree with the other comments that you should be using a FromEvent and ToTask, but you suggest these do not work. Why? I dont think you provide nearly enough of your code base to help with design questions like this. e.g. How are thee nondeterministic task being created? and by what? What is the actual problem you are trying to solve. If you could provide a full example, you might get the amount of attention you are looking for.

On The Subject Of Subjects (in RxJS) - Ben Lesh, While this is helpful for people new to RxJS (and in that capacity Well, for one thing, it shows why you don't always need to use a Subject, and for another When you call subscribe with an observer on an Rx Subject, it will  Rx.NET implements this operator as StartWith. It accepts an array of items which it prepends to the resulting Observable sequence in the order they appear in the array before it emits the items from the source Observable.

Here is what a good book about the Rx says regarding why and when Subject can be harmful:

"Avoid the use of the subject types. Rx is effectively a functional programming paradigm. Using subjects means we are now managing state, which is potentially mutating. Dealing with both mutating state and asynchronous programming at the same time is very hard to get right. Furthermore, many of the operators (extension methods) have been carefully written to ensure that correct and consistent lifetime of subscriptions and sequences is maintained; when you introduce subjects, you can break this. Future releases may also see significant performance degradation if you explicitly use subjects."

Side effects, NET 4.5. Considering this, if Rx improves our code base then we should embrace it! Side effects are not always accidental, nor are they always intentional. An easy way to Consumers could change the entire subject out if they wanted. If we make some simple changes we can make a class that seems safe enough. That is a very bad trade off in the case of diseases that are most often benign or that the individual may never encounter. In the case of the childhood viral illnesses of yesteryear, they may have even filled an important roll in priming the immune system. Also, everyone is always talking about herd immunity. Well what about the health of the

Lifetime management, Rx provides fine grained control to the lifetime of subscriptions to queries. NET Structured Exception Handling: subject.OnCompleted();. subject.OnNext(2);. Of course, you could implement your own IObservable<T> is effectively a try / finally block that will always call Dispose on your instance when leaving the scope. Firstly a gradual onset, whereby I was feeling increasingly more tested after the combined measleas/rubella vaccine, followed a few weeks later by the polio booster. And then secondly once that prodrome had got its hold, the downward cascade was always inevitable, and just waiting for me around the corner. 1994-2014 were harsh and brutal years.

Subject, Because a Subject subscribes to an Observable, it will trigger that Observable to begin emitting items (if that Observable is Introduction to Rx : AsyncSubject  Natural Grow CBD Oil Product Overview. The Natural Grow Cannabis Supplement is a hemp oil. It says CBD on the bottle, but we don’t have access to a complete Natural Grow RX Product Label, so we can’t say for sure what the concentration of CBD is in this product.

Chapter 1. Reactive programming, Reactive Extensions (Rx) is a library that provides the reactive programming model for . the observers fetch data from the source and always checking whether there's components: subject and observer (not to be confused with IObserver of Rx). When the loading time is longer than a few milliseconds, you get a bad  Another recent trend is including symbols in subject lines, and while this may increase open rates, the jury is out on whether or not it affects clicks. 2. Always send out emails asking for help. Litmus indicates in their infographic that the fear of being scammed has made many consumers wary of emails that always ask for help or assistance. 3.

  • The short answer is no. However, both of these cases can be handled with built in functionality. IObservable<T> ToObservable(this Task<T> task) should handle your task continuation case, and Observable.FromEvent should handle the other. Are these methods too verbose? The both provide more functionality than a simply subject, including being lazy.
  • @ChristopherHarris Thanks, but I'm not sure the first works and I know the second doesn't. The first because I have a non-deterministic number of tasks, and the second because, as noted, this is not a standard event...which FromEvent does not work on
  • When you say "non-deterministic number of tasks all running in parallel", what you really mean is "multiple eagerly invoked tasks", no?
  • @ChristopherHarris yes. They can start at different times, or else a merge would work
  • What's the delegate type for your nonstandard event?
  • See my comment to @ChristopherHarris above as both options do not work for me