Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS: Setting default value for observable from another observable

Tags:

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

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?

like image 259
coquin Avatar asked Aug 29 '16 05:08

coquin


People also ask

What RxJS operators can be used to change from one observable to another?

This map() operator is defined in a pipe where you can modify the content of emitted values from one observable to form another new observable. Inside the pipe, you can add your modification logic; in this case, it converts the emitted values to uppercase.

Is observable sync or async?

An observable produces values over time. An array is created as a static set of values. In a sense, observables are asynchronous where arrays are synchronous. In the following examples, → implies asynchronous value delivery.

What is subscribe in observable?

Subscribing to an Observable is like calling a function, providing callbacks where the data will be delivered to. This is drastically different to event handler APIs like addEventListener / removeEventListener . With observable.subscribe , the given Observer is not registered as a listener in the Observable.

Can observable return multiple values?

The fundamental difference is that observable is able to return multiple values.


1 Answers

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

var userIdStream = Rx.Observable.concat(cookieUserIdStream, userIdRequest).first();
like image 191
Can Nguyen Avatar answered Oct 28 '22 19:10

Can Nguyen