RxJS: Setting default value for observable from another observable

穿精又带淫゛_ 提交于 2019-12-10 14:55:56

问题


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

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?


回答1:


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

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


来源:https://stackoverflow.com/questions/39198958/rxjs-setting-default-value-for-observable-from-another-observable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!