Yuvals
Yuvals

Reputation: 3266

takeUntil does not work with BehaviorSubject

I have the following BehaviorSubject defined:

  private posts = new BehaviorSubject<any[]>([]);

and on init:

ngOnInit() {
  this.posts
    .takeUntil(!this._postsLoaded)
    .subscribe(x => {
       this._postsLoaded = true;
        // do something
    });
}

But it gets the following error, although it should work:

Property 'takeUntil' does not exist on type 'BehaviorSubject<any>'

Upvotes: 1

Views: 2915

Answers (2)

martin
martin

Reputation: 96891

There're two things:

  1. In RxJS 6 you should use pipable operators. If you have to use the old "patch" style of operators you'll need to include rxjs-compat package

  2. The takeUntil() operator takes as a parameter another Observable so what you have now will throw an error anyway.

    Maybe you should use takeWhile() instead. See this answer (RxJS takeWhile but include the last value) if you want to also include the last value that completed the chain.

Upvotes: 0

Jameel Moideen
Jameel Moideen

Reputation: 7931

If you want to use like a chain syntax , You have to install rxjs compat also for backward comptability.

npm install --save rxjs-compat

But I would suggest use pipes

import { takeUntil } from 'rxjs/operators';
ngOnInit() {
  this.posts.pipe(
    takeUntil(!this._postsLoaded)
    ).subscribe(x => {
       this._postsLoaded = true;
        // do something
    };
}

Sample Stackblitz

https://stackblitz.com/edit/rxjs-takeuntilexample?file=index.ts

Upvotes: 3

Related Questions