K
K
Konstantin2020-02-13 15:55:51
Angular
Konstantin, 2020-02-13 15:55:51

Why does ReplaySubject return all values?

I have a service:

private publishSubscribeSubject_: ReplaySubject<any> = new ReplaySubject();
    private emiter_: Observable<any>;
    
    public publish(channel: EventsChannels, event: any) {
       this.publishSubscribeSubject_.next({ channel: channel, event: event });
    }
    
    public subscribe(channel: EventsChannels[] | EventsChannels , handler: (value: any) => void) {
       return this.emiter_
          .filter(emission => emission.channel === channel)
          .map(emission => emission.event)
          .subscribe(handler);
    }


Usage in a component:

ngOnInit() {
        this.objectDetailsSubscription = this.eventService.subscribe(
          EventsChannels.OBJECT_DETAILS,
          semantic => {
            console.log(semantic);
          }
        );
      }


Why every time I activate the component I see all the latest values ​​in `ngOnInit() {}` from `ReplaySubject`?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
ha100790tag, 2020-02-18
@Junart1

because this is how ReplaySubject works )))
if you want to see not all values, but only a limited number - pass this to the first argument, for example: new ReplaySubject(10) will store only the last 10 values. by default, this value is Number.POSITIVE_INFINITY - that is, positive infinity, which means that until js reaches the limit of a familiar number, it will save new and new values ​​and output them accordingly when subscribing.
if the task is to store only the last value with the ability to subscribe to it at any time, then BehaviorSubject is more suitable here
if the question is to show values ​​filtered according to some principle, then try filtering inside the map operator - the filter operator does not transform the value in any way, but only checks whether it is emitted or not emitted.
if your case differs from those described, please describe in the comments what you would like to achieve.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question