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