Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do the various ISubject implementations do and when would they be used?

I have a fairly good idea of what the Subject class does and when to use it, but I've just been looking through the language reference on msdn and see there are various other ISubject implementations such as:

  • AsyncSubject
  • BehaviorSubject
  • ReplaySubject

As the documentation is pretty thin on the ground, whats the point of each of these types and under what situations would you use them?

like image 473
James Hay Avatar asked Jan 24 '11 21:01

James Hay


2 Answers

These subjects all share a common property - they take some (or all) of what gets posted to them via OnNext and record it and play it back to you - i.e. they take a Hot Observable and make it Cold. This means, that if you Subscribe to any of these more than once (i.e. Subscribe => Unsubscribe => Subscribe again), you'll see at least one of the same value again.

ReplaySubject: Every time you subscribe to the Subject, you get the entire history of what has been posted replayed back to you, as fast as possible (or a subset, like the last n items)

AsyncSubject: Always plays back the last item posted and completes, but only after the source has completed. This Subject is awesome for async functions, since you can write them without worrying about race conditions: even if someone Subscribes after the async method completes, they get the result.

BehaviorSubject: Kind of like ReplaySubject but with a buffer of one, so you always get the last thing that was posted. You also can provide an initial value. Always provides one item instantly on Subscribe.

like image 137
Ana Betts Avatar answered Sep 28 '22 21:09

Ana Betts


In light of the latest version (v1.0.2856.0) and to keep this question up to date, there has been a new set of subject classes:

FastSubject, FastBehaviorSubject, FastAsyncSubject and FastReplaySubject

As per the release notes they

are much faster than regular subjects but:

  • don’t decouple producer and consumer by an IScheduler (effectively limiting them to ImmediateScheduler);
  • don’t protect against stack overflow;
  • don’t synchronize input messages.

Fast subjects are used by Publish and Prune operators if no scheduler is specified.

like image 39
James Hay Avatar answered Sep 28 '22 22:09

James Hay