最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Conditionally chain observable - Stack Overflow

programmeradmin1浏览0评论

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

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.
}
Share Improve this question asked Feb 15, 2017 at 23:35 HutchHutch 1,00711 silver badges19 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 21

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();
            }
        });
}
发布评论

评论列表(0)

  1. 暂无评论