Rxjs: Difference between Observable.First vs Single vs Filter

谁说胖子不能爱 提交于 2020-03-18 12:30:15

问题


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?


回答1:


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|--


来源:https://stackoverflow.com/questions/41282149/rxjs-difference-between-observable-first-vs-single-vs-filter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!