K
K
KiBiLizard2019-03-26 20:05:10
JavaScript
KiBiLizard, 2019-03-26 20:05:10

RxJs. why two subscriptions to one observable don't work?

there is an observable created from a Subject:

private searchData$: Observable<ISearchData>;
    
    constructor (private conService: ConnectionService) {
        this.searchData$ = <Observable<ISearchData>>conService.messages.pipe(
            filter((message) => {
                return message.key === QUERYBASE.search.key;
            }),
            map ((message)=>{
                return message.data as ISearchData;
            })
        );
    }

there is a method that sends a request, after which messages appear in messages that pass the filter, and subscribes to searchData$
public startSearch(){
        let queryData: ISearchQueryData = ...

        this.searchDataSub = this.searchData$.subscribe(
            (data)=>{
                console.log("Get search data: ",data);
                if (data.hash !== this.lastHash) {
                    this.items = data.search;
                    this.lastHash = data.hash;
                }
                this.searchDone = data.done;
            }
        );
        const newSub = this.searchData$.pipe(
            delay(2000)
        ).subscribe(
            (data)=> {
                console.log("sub2", data);
                //!data.done && this.conService.search(queryData);
            }
        );

        this.conService.search(queryData);
    }

if you cut out the second subscription, the first one works ("Get search data: , ..." appears in the console, the data is being processed)
and if you leave both, for some reason only the second subscription works !! (there is only "sub2, ..." in the console, there is no data)
Of course, I can insert a crutch and leave only the first subscription in which to send a request after a timeout, but damn it, all the tutorials say that you can do two .subscribe for one observable, and without any frills, so why doesn't it work for me?
I tried to remove .pipe, the same game, only the second subscription works:
this.searchDataSub = this.searchData$.subscribe(
            (data)=>{
                console.log("Get search data: ",data);
                /*...*/
            }
        );
        const newSub = this.searchData$.subscribe(
            (data)=> {
                console.log("sub2", data);
                //...
            }
        );

so in the console only sub2

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dasha Tsiklauri, 2019-03-27
@KiBiLizard

hot vs cold observables

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question