如何使用Rxjs将主题“next”的值合并到主流中

时间:2015-10-13 04:36:22

标签: rxjs

方法重试返回主题时,如何将其下一个值与主流合并?

dataStream.
    retryWhen(errors => {
        return errors.
            delay(1000).
            take(3).
            concat(Rx.Observable.throw(errors));
    }).
    subscribe(
        x => console.log('onNext:', x),
        e => {
            e.subscribe(function (value) {
                console.log('err', value);
            });
        },
        _ => console.log('onCompleted'));

现在它可以工作但我必须在错误处理程序中订阅 e 以获取dataStream抛出的错误的值。有可能简化这个吗?

更新

我想用弹性编写“数据访问例程”。目前它会以1秒的延迟重试3次,如果出现错误,它将抛出“错误”。问题是它不会抛出一个错误,它会抛出一个“主题”,我必须订阅它才能得到错误。

let getPromiseStream = function (endpoint) {
    return Rx.Observable.
        just(endpoint).
        flatMap(requestUrl => {
            return _this.$http.get(requestUrl);
        });
};

let itemsStream = getPromiseStream('/items');
let locksStream = getPromiseStream('/error');
let usersStream = getPromiseStream('/users');
let favsStream = getPromiseStream('/favs');

let dataStream = Rx.Observable.
            zip(
            itemsStream,
            locksStream,
            usersStream,
            favsStream,
            (items, locks, users, favs) => {
                return {items: items.data, locks: locks.data, users: users.data, favs: favs.data};
            });

1 个答案:

答案 0 :(得分:1)

retryWhen可能有点难以使用(我必须再次查看以记住它的行为)。基本上retryWhen会收到您从来源Observable收到的所有错误,并将其转换为onNext次来电。您传入的函数接收 Observable,然后让您玩通过的事件。如果你想继续重试它应该简单地通过事件。如果它应该出错,那么您需要将onNext转换为onError,或者如果您只是希望它停止尝试,那么您应该将其转换为onCompleted

因此,如果您的代码实际上不仅仅是一个短暂的网络错误,那么您希望延迟一定次数,然后将整个错误输出错误。

dataStream.
    retryWhen(errors => {
        return errors
            .flatMap((err, count) => {
              return count < 3 ? 
                //This will just get flattened out and passed through
                Rx.Observable.just(err) :
                //If you have received 3 errors it is time to throw
                //This error will get passed all the way to the final
                //onError method if it isn't caught along the way
                Rx.Observable.throw(err);
            })
            .delay(1000);
    })
    .subscribe(
        x => console.log('onNext:', x),
        e => console.log('err', value),
        _ => console.log('onCompleted'));

补充说明:我建议您将retryWhen放在每个Observablezip,而不是整个内容。Observables。如在后一种情况下,一个人的失败将重试所有eventList=disp(); $(".responsive-calendar").responsiveCalendar({ events:eventList //json object data }); function disp(){ //getArr(); //alert(data1); //not working stb = '{'; edb = '}'; dt = ["2015-09-13","2015-10-22","2015-10-02"]; // dynamically to be created from ajax data ct = [2,5,6]; // dynamically to be created from ajax data ev = dt.length; var ddt = stb; for(var i=0; i<ev;i++){ ddt += '"' + dt[i] + '":{"number":'+ct[i]+'},'; } mString = ddt.substring(0,ddt.length-1) ddt = mString+edb; return JSON.parse(ddt); } function getArr() { $.ajax({ url:"../JLRFile.php", success:function(data) { data1 = data; } }); } 而不仅仅是失败的那个。