Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rxjs: Difference between Observable.First vs Single vs Filter

Tags:

rxjs

I am exploring RxJS library and really a fan of using Observable instead of Promise. However, can someone provide any detailed information about the difference between using

  • Observable.First
  • Observable.Single
  • Apply Filter in such a way that it returns only single item

What is the need for Single specifically in this library?

like image 566
Sachin Gaur Avatar asked Dec 22 '16 11:12

Sachin Gaur


People also ask

What is the difference between the take 1 and first () actions?

first() vs take(1) The difference is when there are no elements in the input stream. In this case, first() throws an Error, while take(1) closes the Observable without any elements. When you are sure that the input Observable is not empty, it's safer to use first() as it will report the empty case as an error.

What is first Observable?

RxJS first() operator is a filtering operator that emits only the first value or the first value that meets some specified condition emitted by the source observable.

What is the difference between Observable and a subject in RxJS?

An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast. A Subject is like an Observable, but can multicast to many Observers.

What is the use of first () in angular?

The first operator emits the first value that meets the condition. If no condition is specified, then it will emit the first value it receives. If the source completes before emitting any matching value, then it raises the error notification.


1 Answers

If by filter you mean something like:

let emitted = false;
obs = obs.filter(x => {
  if(emitted) {
    return false;
  } else {
    emitted = true;
    return true;
  }
});

Filter (in this particular case, check the code above)

Will emit as soon as first item appears. Will ignore all subsequent items. Will complete when source observable completes.

in : -1-2-3--|---
out: -1------|---

First

Will emit as soon as first item appears. Will complete right after that.

in : -1-2-3--|---
out: -1|----------

Single

Will fail if source observable emits several events.

in : -1-2-3--|---
out: -1-X---------

Will emit when source observable completes (and single can be sure nothing more can be emitted). Will complete right after that.

in : -1------|---
out: --------1|--
like image 95
Sergey Sokolov Avatar answered Nov 10 '22 17:11

Sergey Sokolov