RxJS:从另一个 observable 设置 observable 的默认值 [英] RxJS: Setting default value for observable from another observable

查看:48
本文介绍了RxJS:从另一个 observable 设置 observable 的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建可观察流,它从 cookie 中获取用户 ID,如果在 cookie 中找不到,则从 API 中获取它.我如何在 RxJS 中做到这一点?

I'm trying to create observable stream which takes user id from cookie and, if not found in cookie, fetches it from API. How can I do it in RxJS?

var userIdRequest = Rx.Observable.bindCallback(generateIdAsync);
var cookieUserIdStream = Rx.Observable.of(getCookieValue("user_id"))
    .filter(x => x !== null);

var userIdStream = cookieUserIdStream.__ifEmptyThen__(userIdRequest()); // <<< ???

// Emulating async request for user id
// Will be a JSONp call in real app
function generateIdAsync(cb) {
    setTimeout(() => {
        cb(`id_${new Date().getTime()}`);
    }, 300);
}

function getCookieValue(name) {
    var regexp = new RegExp(`${name}=([^;]*)`);
    var match = document.cookie.match(regexp);

    return match && match[1];
}

有一个 defaultIfEmpty 方法,它只适用于简单的值,而不适用于 observables.在 Bacon.js 中有用于流的 or 方法,它工作得非常好,但我在 RxJS 中没有看到任何类似的东西.我是否遗漏了什么或我需要实现自定义观察者?

There's a defaultIfEmpty method which works with simple values only, not with observables. In Bacon.js there's or method for streams, which works perfectly fine, but I don't see anything similar in RxJS. Do I miss something or do I need to implement a custom observer?

推荐答案

您可以连接 2 个 observable 并获得第一个发出的值:

You may concat the 2 observables and get the first emitted value:

var userIdStream = Rx.Observable.concat(cookieUserIdStream, userIdRequest).first();

这篇关于RxJS:从另一个 observable 设置 observable 的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆