take(1) vs first()

June 2021

Are take(1) and first() the same? No. Learn what’s the difference.

take(1)

first

Example

  result = {};
  ngOnInit() {
    EMPTY.pipe(take(1)).subscribe(
      next => (this.result['take1'] = next),
      err => (this.result['take1'] = err)
    );
    EMPTY.pipe(first()).subscribe(
      next => (this.result['first'] = next),
      err => (this.result['first'] = err)
    );
  }

Result:

{
  "first": {
    "message": "no elements in sequence",
    "name": "EmptyError"
  }
}

Full example: https://stackblitz.com/edit/first-vs-take

Good SO answer regarding this: https://stackoverflow.com/a/42346203/3022127

Which one should you choose?

Here this SO answer is very useful: https://stackoverflow.com/a/54209901/3022127.

Become a better web developer by staying up to date