7

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?

Sachin Gaur
  • 12,909
  • 9
  • 33
  • 38

1 Answers1

10

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|--
Sergey Sokolov
  • 2,709
  • 20
  • 31
  • 2
    Just to add a note to avoid confusion by future readers- `filter` by itself doesn't ignore subsequent items. It only does so here in your example because a boolean is set (as designed). The behavior is clear if reading your example code, but at first glance it looks like these are generic descriptions of the different operators. You did answer the questioner who wanted `Apply Filter in such a way that it returns only single item` although I'm not sure why you'd ever want to do that. It would be super confusing to someone who read it later! – Simon_Weaver Jan 10 '19 at 07:39