Return an empty Observable

前端 未结 11 1048
北荒
北荒 2020-11-30 18:23

The function more() is supposed to return an Observable from a get request

export class Collection{

    public more = (): Observab         


        
11条回答
  •  误落风尘
    2020-11-30 18:57

    With the new syntax of RxJS 5.5+, this becomes as the following:

    // RxJS 6
    import { EMPTY, empty, of } from "rxjs";
    
    // rxjs 5.5+ (<6)
    import { empty } from "rxjs/observable/empty";
    import { of } from "rxjs/observable/of";
    
    empty(); // deprecated use EMPTY
    EMPTY;
    of({});
    

    Just one thing to keep in mind, EMPTY completes the observable, so it won't trigger next in your stream, but only completes. So if you have, for instance, tap, they might not get trigger as you wish (see an example below).

    Whereas of({}) creates an Observable and emits next with a value of {} and then it completes the Observable.

    E.g.:

    EMPTY.pipe(
        tap(() => console.warn("i will not reach here, as i am complete"))
    ).subscribe();
    
    of({}).pipe(
        tap(() => console.warn("i will reach here and complete"))
    ).subscribe();
    

提交回复
热议问题