Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally chain observable

For the following TypeScript (using rxjs):

getRegularData(): Observable<MyData> {
    return WS.loadRegularData();
}

getAlternateData(): Observable<MyData> {
    return WS.loadAlternateData();
}

how can a new method be implemented to satisfy the following pseudocode:

getData(): Observable<MyData> {
    // try to use getRegularData, and return observable for result.
    // if getRegularData returns null, get data from getAlternateData()
    // instead and return observable for result.
}
like image 439
Hutch Avatar asked Feb 15 '17 23:02

Hutch


1 Answers

There are many ways you can implement this, one would be to use a switchMap that contains your condition:

getData(): Observable<MyData> {
    return getRegularData()
        .switchMap(data => {
            if (data != null) {
                return Observable.of(data);
            } else {
                return getAlternateData();
            }
        });
}
like image 81
olsn Avatar answered Sep 18 '22 00:09

olsn