K
K
kolyalesha2017-10-30 15:50:51
JavaScript
kolyalesha, 2017-10-30 15:50:51

Rxjs switchMap, why how many subscribe so many requests?

query() {
    сonsole.log('query');
}

let search$ = new BehaviorSubject('');
let x = search$
       .distinctUntilChanged()
       .do(() => console.log('search called!'))
       .mergeMap(() => query());
x.subscribe(data => console.log('data'));
x.subscribe(data => console.log('data'));
x.subscribe(data => console.log('data'));
x.subscribe(data => console.log('data'));

query
data
query
data
query
data
query
data

Then if the search changes again outputs
search$.next('asd');
query
data
query
data
query
data
query
data

The problem is that 4 requests flies each time (how many subscribe and requests)
How to make it so that when the search$ changes, the query() method is called ONCE and all callbacks are processed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sasha Novik, 2017-10-31
@kolyalesha

For each subscribe, the whole chain works out, such is the behavior.
Fast decision:

let x = search$
       .distinctUntilChanged()
       .do(() => console.log('search called!'))
       .mergeMap(() => query())
       .shareReplay(1);

Useful reading to deal with cold and hot Observables: https://medium.com/@benlesh/hot-vs-cold-observable...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question