Unsubscribe before second subscription

Discussão em 'Angular' iniciado por Kostiantyn Okhotnyk, Dezembro 3, 2024.

  1. How unsubscribe in rxjs before second subscription of Subject without takeUntil? I have DI service with a lot of chunks observables. For simplify I shorted it for one problem.

    const test$ = new Subject();

    function someFunctionSub(n) {
    this.destroy$.next(true);
    test$.pipe(takeUntil(this.destroy$)).subscribe((res) => console.log(n));
    }

    someFunctionSub(1); // first sub
    test$.next(true);

    setTimeout(() => {
    someFunctionSub(2); // second sub
    }
    , 1000);



    I need to unsubscribe before the second subscription call. But this.destroy$.next(true); It confuses me because I need 100500 times it call (it just in example one destroy$.next)

    I trying switchMap but it not work for several subscriptions.

    const test$ = new Subject();

    function someFunctionSub(n) {

    test$.pipe(switchMap(res => of(res)).subscribe((res) => console.log(n));
    }

    someFunctionSub(1); // first sub
    test$.next(true);

    setTimeout(() => {
    someFunctionSub(2); // second sub
    }
    , 1000);

    //1
    //1 - side effect several subscriptions
    //2



    take(1) it also not work because there is no guarantee that next will work for example

    const test$ = new Subject();

    function someFunctionSub(n) {

    test$.pipe(switchMap(res => of(res)).subscribe((res) => console.log(n));
    }

    someFunctionSub(1); // first sub
    // test$.next(true); It can't call

    setTimeout(() => {
    someFunctionSub(2); // second sub
    test$.next(true);
    }
    , 1000);

    //1 - side effect several subscriptions
    //2 - i need only 2

    Continue reading...

Compartilhe esta Página