返回条件rxjs Observable的更好方法

时间:2017-05-05 11:01:09

标签: typescript rxjs rxjs5

在以下代码中,函数onReady1()onReady2()是否相同?有什么区别?有没有更好的方法来编写这个功能?

onReadyx()函数应该返回用户,如果它可用,或者它会等到它可用。在任何给定时间都会有多次调用此函数。

export class UserService {
    private _user: IUser;

    private userObservable: Observable<IUser>;

    constructor(private http: Http) {
        this.userObservable = this.getCurrentUser();
    }

    public onReady1() {
        return Observable.create((observer: Observer<IUser>) => {
            if (this._user) {
                observer.next(this._user);
                observer.complete();
                return;
            }

            this.userObservable.subscribe(user => {
                this._user = user;
                observer.next(user);
                observer.complete();
            });
        });
    }

    public onReady2() {
        return Observable.defer(() => {
            if (this._user) {
                return Observable.of(this._user);
            }

            return this.userObservable.do(user => this._user = user);
        });
    }

    private getCurrentUser() {
        return this.http.get('/currentuser')
            .map(response => response.json() as IUser);
    }

}

1 个答案:

答案 0 :(得分:2)

使用publishLast

export class Service {
  private sharedStream$: Observable< IUser>;

 constructor(public http: AuthHttp) {
   this.sharedStream$ = this. getCurrentUser()
    .publishLast()
    .refCount();
 }

 getUserObservable(): Observable< IUser> {
  return this.sharedStream$;
 }
}