Hutch
Hutch

Reputation: 1007

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.
}

Upvotes: 7

Views: 8341

Answers (1)

Olaf Horstmann
Olaf Horstmann

Reputation: 16892

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

Upvotes: 21

Related Questions