What are RxJS Subject's and the benefits of using them? - javascript

I found the rxJS docs define them as
What is a Subject? An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast.
and it goes on to give examples but I'm looking for a basic ELI5 explanation. From my understanding is it helps handle and define items in a sequence. Is that correct?
I think it would be most helpful to me and others to see a simple function with and without defining an rxJS Subject to understand why it's important?
Thanks!

The easiest way to understand it is to think of a Subject as both a producer and a consumer. It's like an open channel where someone can send a message on one end, and any subscribers will receive it on the other end.
+---------------
Sender | => => => => Subscriber
-----------------------+ +-----------
Message => => => => => => => => => => => Subscriber
-----------------------+ +-----------
| => => => => Subscriber
+---------------
In code terms say you have a service with a subject
class MessageService {
private _messages = new Subject<Message>();
get messages: Observable<Message> {
return this._messages.asObservable();
}
sendMessage(message: Message) {
this._messages.next(message);
}
}
Note the messages getter returning the Subject as an Observable. This is not required. The Subject is already an observable, and anybody could subscribe directly to the Subject. But I think the asObservable pattern is used as a way to limit what users can do with it, i.e. so users only use it to subscribe to, and not emit to. We save the emitting for the sendMessage method.
Now with this service in place, we can inject it into different components, and this can be a way for two (or more) arbitrary components to communicate (or just receive arbitrary event notifications).
class ComponentOne {
constructor(private messages: MessageService) {}
onClick() {
this.messages.sendMessage(new Message(..));
}
}
class ComponentTwo {
constructor(private messages: MessageService) {}
ngOnInit() {
this.messages.messages.subscribe((message: Message) => {
this.message = message;
});
}
}
Angular's own EventEmitter is actually a Subject. When we subscribe to the EventEmitter, we are subscribing to a Subject, and when we emit on the EventEmitter, we are sending a message through the Subject for all subscribers.
See also:
Subject vs BehaviorSubject vs ReplaySubject in Angular

Subjects are useful when the code you're in is the one that is actually originating the observable data. You can easily let your consumers subscribe to the Subject and then call the next() function to push data into the pipeline.
If, however, you are getting data from other source and are just passing it along (perhaps transforming it first), then you most likely want to use one of the creation operators shown here, such as Rx.Observable.fromEvent like so:
var clicks = Rx.Observable.fromEvent(document, 'click');
clicks.subscribe(x => console.log(x));
This allow you to stay in the functional paradigm, whereas using a Subject, while it has its uses, is considered by some to be a smell that you're trying to force imperative code into a declarative framework.
Here is a great answer that explains the difference in the two paradigms.

If you want the most simple explanation ...
Observables are usually the result of something. The result of an http call, and whatever you do with a pipe returns an observable.
But what is the source of those things? Ever wondered how you hook your user events into the whole rxjs thing? The main feature of subjects is that you can call the next() method on them.
When doing reactive programming, the first step is usually to make a list of possible subject you will have.
For instance: lets say we have to make a todo-list app.
We will probably have a couple of variables in our component:
public deleteItem$ = Subject<TodoItem> = new Subject();
public addItem$ = Subject<TodoItem> = new Subject();
public saveList$ = Subject<TodoItem[]> = new Subject();
and in our applicatiuon we will hook these up like this:
<button (click)="deleteItem$.next(item)">Delete</button>
Using rxjs, we will use operators like merge/combineLatest/withLatestFrom to handle these subjects and define our application logic.
I'll see if I can find the time to make a small example.

You can find a study of the semantics of subjects here.
All answered I see are correct. I'll just add that the term subject comes from the observer pattern (cf. https://en.wikipedia.org/wiki/Observer_pattern). As such a subject is sort of a relay, it receives something on one end, and emit it on any of its ends (subscriptions).

Related

Typescript RXJS Subject await async susbscriptions

Suppose I have two completely independent pieces of code in two completely unrelated classes that subscribe to the same Observable in a service class.
class MyService {
private readonly subject = new Subject<any>();
public observe(): Observable<any> {
return this.subject.pipe();
}
}
class A {
constructor(private readonly service: MyService) {
service.observe().subscribe( async (value) => {
await this.awaitAnOperation(value);
console.log('Class A subscription complete', value);
});
}
}
class B {
constructor(private readonly service: MyService) {
service.observe().subscribe( (value) => console.log('Class B subscription complete', value));
}
}
The issue that I am now facing is that when the service emits an event, the log of class B will come before A, even though A subscribed first. What I need is that all methods are ran and finished before going to the next one. I know if A were to be synchronously than my question would be solved, but A does need to run an async operation AND Bcan only log after A has logged.
A and B are completely unaware of eachother and should be as well. In e.g. C# we can run an async method synchrnonously by using GetAwaiter().Wait(); and is not considered a bad practice since when it needs to run on the main thread. An equivalent TS/JS option would be nice.
EDIT
A subscribes before B. It is simply the chronological order of subscribing that should also execute. I know this is by default emitted in that sequence, but the fact remains that running a subscription method on a different thread would continue the main thread to the next subscription. This is what I need to avoid somehow.
I had a similar issue that I solved with an operator I called forkConcat. Instead of subscribing multiple times, I made multiple operators and chained them so that source$.pipe(operatorA) would happen and complete before source$.pipe(operatorB) started, and that would complete before source$.pipe(operatorC) started, and all three completed before dealing with the next value from source$.
My code looked like this...
source$.pipe(
forkConcat(
concat,
operatorA,
operatorB,
operatorC
) )
where forkConcat is defined as
import { merge, Observable, of } from 'rxjs';
import { concatMap, Operator } from 'rxjs/operators';
/*
Creates an operator that will fork several operators from the same input, and not proceed until all those things are done.
First Argument:
If those things should be done in turn, send concat as the first argument.
If each operator should be done in parallel, use merge (or undefined) as the first argument.
To return an array of each operators' final values per value received by forkConcat, use forkJoin.
You could also use combineLatest, etc.
All other arguments are operators.
*/
type Combiner<T> = (...array$: ObservableInput<T>[]) => Observable<T>;
export function forkConcat<T,R>(combiner: Combiner<T> = merge, ...arrayOperators: Operator<T, R>[]) {
return concatMap<T,R>((x) => {
try {
const x$ = of(x);
const o = arrayOperators
.filter(op => !!op) // ignore falsy arguments
.map(op => x$.pipe(op));
return o.length ? combiner(...o) : x$;
} catch (e) {
throw new ForkConcatError(x, e, combiner, arrayOperators);
}
});
}
class ForkConcatError<T> extends Error {
constructor(
readonly receivedValue: T,
readonly innerError: Error,
readonly combiner: Combiner<T>,
readonly arrayOperators: Operator<T, R>[]
) {
super(innerError.message);
}
}
It worked. But I've also got to tell you...
I threw it away
I slowly began to realize that the need for forkConcat was a sign that I should be doing things differently. I haven't seen your code but when you say they shouldn't know about each other yet one affects the other, I highly suspect you should consider the same. If, instead of global/shared variables, you had global/shared subjects and observables where the one that emitted to B was...
source$.pipe(
concatMap(x => concat(
of(x).pipe(
operatorA,
ignoreElwments()
),
of(x) // B should receive the same value A did.
)
)
... then you wouldn't have this issue and your code would be cleaner.
In my case, I went a different route. I made a State interface, and then instead of passing source values through my operators, I passed {source: Source, state: State} objects. This way, there was no longer any global variables at all! Every operator could be a pure function (or pure function plus side effects) using only the combined value/state pairs emitted into them. State errors were much harder to make! To use this tactic, start thinking of your A and B as operators (that don't know about each other) instead of subscribers (that don't know about each other) and your future self will likely be happier.
But just in case I'm wrong about that advice, you now have forkConcat.
You can do that by combining the two Observables using switchMap rxjs operator. it will be guarantied that the second Observable B will not started unless the first one A is done.
Here a good example to this scenario in the section addressed "Combining Observables in series":
https://blog.danieleghidoli.it/2016/10/22/http-rxjs-observables-angular/

What is the difference between subscribing to subject and subscribing to asObservable?

What is the difference between subscribing to subject and subscribing to asObservable?
What is the difference between the following?
this.subject.subscribe((data) => this.datas.push(data));
this.subject.asObservable().subscribe((data) => this.datas.push(data));
Seems like both are same!
From the subscription side, there is no difference; emissions are received exactly the same.
asObservable() is used to hide the Observer behavior from consumers, preventing them from nexting values into the subject.
In angular, you'll see this in a lot services where you want consumers of the service to have access to the emitted values, but you don't want them to be able to call .next on the subject:
class SomeService {
private subject$ = new Subject();
public observable$ = this.subject$.asObservable();
}

How to pass a value from a service, to a component's method

I've got a service that I use to share data between 2 components. That part works flawlessly, but now I need to call a method of component A, when something triggers on the service (and pass a value to that component). How can I do this? I read on older questions that this is a wrong approach but since Im a noob I dont know what to search for a solution.
Do I need to use observables?
I think Joseph's idea is the way to go.
Here's how I'd implement it:
class FooService {
private _newEvents = new Subject();
newEvents$ = this._newEvents.asObservable();
addNewEvent (ev) {
this._newEvents.next(e);
}
}
// Allow `A` class to communicate with `B` class
class A {
addEvent (ev) {
this.fooService.addNewEvent(ev);
}
}
class B {
private subscription: Subscription;
ngOnInit () {
this.subscription = this.fooService.newEvents$
.subscribe(e => {})
}
ngOnDestroy () {
this.subscription.unsubscribe();
}
}
Note that if your B class subscribes to multiple observables, you should unsubscribe from them using, among other solutions, takeUntil.
Observables / Subjects are one way. You would have one Subject in the service, and would use .next(value) on it to exchange values. Each component which is interested in the value may subscribe to that subject.
Example: (taken from RxJS docs
//your Service
import { Subject } from 'rxjs';
const subject = new Subject<number>();
//Component A (and others as well)
service.subject.subscribe({
next: (num) => console.log(num)
});
//this should work as well with prettier syntax:
service.subject.subscribe(sum =>
console.log(num)
);
//Component B
service.subject.next(7) //passing number 7 to Component A
Whenever you create a subscription, make sure to always unsubscribe! Else you might end up with stacks of subscriptions, which will all get triggered simultaneously in the very same component.
From personal experience, I found it more helpful to outsource any functions and variables that could be considered as global into a dedicated service, if possible. If you directly read the variables of a service from your components (and modify them if necessary), you'll have the same effect. That works as long as you keep a proper service structure. Some examples of dedicated services with global use are:
Translations (TranslationService)
Rights Management (PermissionService)

What are the differences between using a Subject and an Observable, and what are the uses for each?

I have learned of two different ways of making an Observable. First one was with a Subject, like so:
// file A
const message$ = new Subject();
// file B
message$.subscribe( (message) => console.log(message) );
// file C
message$.next("Hello there!");
This method of creating an Observable allows me to have a way to exchange data from file B to file C.
The second way is via the Observable class, like so:
// file A
const click$ = new Observable( function(observer) {
//Alternatively, I can use Observable.create()
document.addEventListener('click', (e) => observer.next(e));
});
// file B
click$.subscribe( (cl) => console.log(cl) );
The main difference that I can gather between the Subject way and the Observable way is that I am not sure how to have some sort of communication between some file C, to the subscribers of the Observable. Basically, click$ does not have a .next() method, and the observer methods are in the function that we pass to the observable.
Other than this difference in behavior, is there another difference between observables made with Subject, and those made with Observable
A Subject is both Observable and Observer at the same time. That makes it so tempting to use, because you get a reference to an Observer that you can pass around in your code and emit items from wherever you want. However, that increases the error-proneness of your code by a lot, as you switch from a declarative definition of your Observable to a imperative one.
Generally speaking, you should use Observable creation functions (of, from, create) wherever possible. I'd say most cases can be solved without Subjects. There is a steep learning-curve though, as you must get to know most of the Observable creation functions in order to follow that pattern.
Subject might come more natural to developers who are used to code imperatively (that is: with a script language like JS), as it kind of resembles a simple wrapper object for a callback function. And one might ask, why is there a Subject anyway if its not desirable.
According to this article, Subjects are to be used in one case only:
To generate a hot observable imperatively and statefully, without any direct external source.
In short, that means: Use Subject when you don't have any external source (like an Observable, Promise or Event) and need to multicast the state of a class from inside a function. You shouldn't expose that Subject to others, though!
I suggest reading this article to you, it will clear up things.
Subject implements both the Observable and the Observer interface.
Implementing the Observable interface means, among other things, that you can subscribe to a Subject.
Implementing the Observer interface means, among other things, that with a Subject you can call the methods next error and complete.
You create Observables using Subject in the case you want to control programmatically the flow of events of that Observable, which is the case you mentioned of managing communication between C and B.
The relation between Subject and Observable goes like this:
class Observable {}
class Subject extends Observable {}
Subject implements Subscriber interface. So you can use Subject as a Subscriber (Observable cannot be used like this):
const subj = new Subject()
observable.subscribe(subj)
Subject can hide it's Subscriber interface by calling asObservable method - turning Subject into plain Observable;
I generally use Subject when my code is going to generate events and I use Observable when I already have some source of events
For example using Subject as a queue:
const queue = new Subject();
queue.pipe(
concatMap(doStuff)
).subscribe()
queue.next('do this')
queue.next('do that')
or using Subject as a signaller to stop other Observable
const stop = new Subject();
someObservable.pipe(
map(x => x + 1)
takeUntil(stop)
)
// somewhere in my code
stop.next()
Other than this difference in behavior, is there another difference between observables made with Subject, and those made with Observable
I wouldn't say there are differences - It is more like Subject is a complement to plain Observable - allowing us to do more things when needed.

What is the difference between Observable and a Subject in rxjs?

I was going through this blog and reading about Observables and couldn't figure out the difference between the Observable and a Subject.
In stream programming there are two main interfaces: Observable and Observer.
Observable is for the consumer, it can be transformed and subscribed:
observable.map(x => ...).filter(x => ...).subscribe(x => ...)
Observer is the interface which is used to feed an observable source:
observer.next(newItem)
We can create new Observable with an Observer:
var observable = Observable.create(observer => {
observer.next('first');
observer.next('second');
...
});
observable.map(x => ...).filter(x => ...).subscribe(x => ...)
Or, we can use a Subject which implements both the Observable and the Observer interfaces:
var source = new Subject();
source.map(x => ...).filter(x => ...).subscribe(x => ...)
source.next('first')
source.next('second')
Observables are unicast by design and Subjects are multicast by design.
If you look at the below example, each subscription receives the different values as observables developed as unicast by design.
import {Observable} from 'rxjs';
let obs = Observable.create(observer=>{
observer.next(Math.random());
})
obs.subscribe(res=>{
console.log('subscription a :', res); //subscription a :0.2859800202682865
});
obs.subscribe(res=>{
console.log('subscription b :', res); //subscription b :0.694302021731573
});
This could be weird if you are expecting the same values on both the subscription.
We can overcome this issue using Subjects. Subjects is similar to event-emitter and it does not invoke for each subscription. Consider the below example.
import {Subject} from 'rxjs';
let obs = new Subject();
obs.subscribe(res=>{
console.log('subscription a :', res); // subscription a : 0.91767565496093
});
obs.subscribe(res=>{
console.log('subscription b :', res);// subscription b : 0.91767565496093
});
obs.next(Math.random());
Both of the subscriptions got the same output value!
Observables
They are cold: Code gets executed when they have at least a single observer.
Creates copy of data: Observable creates copy of data for each observer.
Uni-directional: Observer can not assign value to observable(origin/master).
The code will run for each observer . If its a HTTP call, it gets called for each observer.
if its a service we want to share among all the components, it wont have latest result all new subscribers will still subscribe to same observable and get value from scratch
Unicast means can emit values from the observable not from any other component.
Subject
They are hot: code gets executed and value gets broadcast even if there is no observer.
Shares data: Same data get shared between all observers.
bi-directional: Observer can assign value to observable(origin/master).
If are using using subject then you miss all the values that are broadcast before creation of observer. So here comes Replay Subject
multicast, can cast values to multiple subscribers and can act as both subscribers and emmitter
I found the accepted answer slightly confusing!
An Observer isn't the interface for feeding an Observable source, it's the interface for observing an Observable source... which makes more sense from the name, right?
So, the reason that:
var observable = Observable.create(observer => {
observer.next('first');
observer.next('second');
...
});
works - creating an observable which emits 'first' then 'second' - is that the argument to Observable.create(...) is a subscribe function, it basically defines which Observer events will happen on a direct Observer of that Observable.
If you want to go into it a little bit further again, it's important to understand that the subscribe function isn't directly called on the Observer object when you subscribe, instead it's mediated by a Subscription object which can enforce correct observable rules, e.g. that an Observable will never emit a new value after observer.complete() has been called, even if your subscribe function looks as if it would.
REF: http://reactivex.io/rxjs/manual/overview.html#creating-observables
A Subject is both an Observable and an Observer and once again it looks just like the Observer interface is the way to 'feed' events to the Subject. But it's easier to understand the naming if you realise that a Subject is a bit like an Observable with the equivalent of the subscribe function (i.e. where you define what events will happen to things observing it) sitting there right on the object, even after it has been created. So, you call Observer methods on the Subject to define what Observer events will happen on things observing it! 😊 (And again, there are intermediate objects involved, to make sure that you can only do legal sequences of things.)
REF: http://reactivex.io/rxjs/manual/overview.html#subject
See rxjs document (more information and examples there):
http://reactivex.io/rxjs/manual/overview.html#subject
What is a Subject? An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast.
A Subject is like an Observable, but can multicast to many Observers. Subjects are like EventEmitters: they maintain a registry of many listeners.
and code, Subject extending Observable: https://github.com/ReactiveX/rxjs/blob/master/src/internal/Subject.ts#L22
/**
* #class Subject<T>
*/
export class Subject<T> extends Observable<T> implements SubscriptionLike {
//...
}
Imagine if you have a stream of data coming into your application like in a websocket connection. You want a way to handle it. There is a few solution:
1. normal ajax request:
This solution is not viable because it is
not applicable to process push data. It is more of a pull then a
push.
2. Promise:
Also not good because you have to trigger them and
they can only retrieve once. Also more of a pull then a push.
So in order to retrieve this data, in the old time, we do a long-polling. Which is where we set an interval function to retrieve that stream of data every 1 minute for an example. Though it works, it actually burdening resources like CPU and memory.
But now with option no 3,
3. Observable: You can subscribe and let the stream of data to come
in non-stop until the function complete has been called.
Cool right ? But then there is another problem. What if you want to observe incoming data only once somewhere in your application. But you want to use that data simultaneously around your application when the data arrived. That is when and where you use Subject.
You place subject.subscribe() at places you want to use throughout your application. When the data arrived, places where there is subject.subscribe() will process them simultaneously. But the observer must subscribe with the subject as its argument like this.
observer.subscribe(subject).
Example application is when you want to build a notification alert.
You cannot have multiple subscription of the same observable because chances are, each subscribers will received different input data. But with subject, all that subscribe() through subject will be retrieving the same data.
Another analogy is through magazine subscription. Each subscribers will received the magazine with their name on it. So, different subscription = different receiver name.(Normal Observable)
But when you share with your friends, all of your friend would receive the same magazine with only your name on it.(Normal Observable with Subject)
This guy explain it very well with code example. You can check it out at https://javascript.tutorialhorizon.com/2017/03/23/rxjs-subject-vs-observable/
Hopefully this answer helps.
Briefly,
subject: you can send to it and receive from it.
Observable: you can receive from it only.
In another words,
In subject you can subscribe to it and you can use it to broadcast to other subscribers any time and anywhere in code.
whilst,
in observable you can subscribe to it only (you can't use it to broadcast data after it have been initialized).
The only place you can broadcast data from observable is inside its constructor.
Observable can inform only one observer, while Subject can inform multiple observers.
From another perspective, it is good to note that the subscription to an Observable re-execute the Observable function. This can lead performance issue if the data source is a service for instance.
If you want several subscribers to get the same value, you may need a Subject.
For this, make sure that your subscription is set before the Subject subscribed to the data source. Otherwise, your process would be stuck.
More details here: https://javascript.tutorialhorizon.com/2017/03/23/rxjs-subject-vs-observable/
Observable:
Only the Observable knows how and when the events are triggered on the observable. i.e the next() method has to be called only inside the instantiated constructor. Also, on subscribing each time, a separate observer is created and calls next() method using particular observer inside constructor only, in the following example subscriber itself is the observer and it is subscribed when the instantiated constructor gets executed.
Ex:
import { Observable } from 'rxjs';
const observable = new Observable(subscriber => {
subscriber.next(1);
subscriber.next(2);
setTimeout(() => {
subscriber.next(3);
}, 1000);
});
Subject:
Here next() method can be used by subject anywhere outside the constructor. Also, when next() method is called before subscribing, the particular event will be missed. Hence next() method has to be called only after subscribing.
Ex:
import { Subject } from 'rxjs';
const subject = new Subject<number>();
subject.next(1); // this is missed
subject.subscribe({
next: (v) => console.log(`observerA: ${v}`)
});
subject.subscribe({
next: (v) => console.log(`observerB: ${v}`)
});
subject.next(2);

Categories

Resources