Home > front end >  How to create new Subject for object?
How to create new Subject for object?

Time:11-24

How to create new Subject for object, or I have to use only Behavior subject?

public myObject: Subject<any> =
    new Subject();

I set data:

myObject.next({id: 1, name: 'Jack'})

and subscribed this subject like this:

myObject.subscribe((res)=> console.log(res))

But I am not able to get data in the subject

CodePudding user response:

Try changing it to BehaviorSubject

public myObject: BehaviorSubject<any> =
    new BehaviorSubject();

CodePudding user response:

The difference between a Subject and a BehaviorSubject is subtle and has to do with the moment of subscribing.

A Subject will only get new values from the moment subscribed.
A BehaviourSubject will give the last value and all new values when subscribing.
There's also a ReplaySubject that will give all previous values and all the new values when subscribing.

CodePudding user response:

[...] or I have to use only Behavior subject?

Not only, but it would help in your example. A BehaviorSubject has a state and whenever you subscribe to it, it will emit the state immediately, e.g.

// set initial state in constructor.
public myObject: Subject<any> = new BehaviorSubject({id: 1, name: 'Jack'});

// calling next will also change the state
myObject.next({id: 2, name: 'Jack-2'});

// emits the state immediately at subscribe.
myObject.subscribe((res)=> console.log(res))

A normal Subject on the other hand does not store any emitted valus. When you call myObject.next({id: 1, name: 'Jack'}) and no one subscribed to myObject the emission is simply lost.

Your thrid option is a ReplaySubject, which will store the n last emissions and emit all of them on subscription.

  • Related