2017-05-05 63 views
1

在下面的代碼中,函數onReady1()onReady2()等效?有什麼區別?有沒有更好的方法來寫這個函數?更好的方式來返回條件rxjs Observable

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); 
    } 

} 
+0

爲什麼要那樣做?你想緩存用戶嗎? – n00dl3

+0

@ n00dl3是的。我在'IUser'中得到了一個令牌,我想用它來進行後續的服務調用。 – nullDev

+0

然後去@JuliaPassynkova的解決方案。 – n00dl3

回答

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$; 
} 
} 
相關問題