Rxjs订阅直到另一个事件发生

时间:2017-10-27 00:42:00

标签: rxjs

我是Rxjs的新手,我正在尝试实现以下工作流程:

  1. 用户点击触发HTTP请求的菜单项
  2. 在响应到达之前,用户点击第二个请求
  3. 结束对第一个请求的订阅,并开始订阅第二个请求

    // The code below sits inside the onClick event of my menu
    var callAction = function(someParameters) {
                return Rx.Observable.create(function(observer) {
                    var subscribed = true;
                    myHttpApi.someActionCall(someParameters).then(
                        (data: any) => {
                            if (subscribed) {
                                // Send data to the client
                                observer.next(data);
                                // Immediately complete the sequence
                                observer.complete();
                            }
    
    
                        }).catch((err: any) => {
                            if (subscribed) {
                                // Inform the client that an error occurred.
                                observer.error(ex);
                            }
    
                        }
                    );
                    return function () {
                        subscribed = false;
                    }
                });
            };
    
  4. 观察员进一步定义如下:

    var observer = {
                    // onNext in RxJS 4
                    next: function (data) {
                        // Do what you need to do in the interface
                    },
                    // onError in RxJS 4
                    error: function (err) {
                        // Handle the error in the interface
                    },
                    // onComplete in RxJS 4
                    complete: function () {
                        //console.log("The asynchronous operation has completed.");
                    }
                };
    
                let subscription = callAction(somParameters).subscribe(observer);
    

    我现在如何实现#3,从而结束对第一个请求的订阅并订阅新请求(在此示例中,针对不同的菜单选项执行相同的代码块,因此基于不同的请求在参数上)开始了吗?

1 个答案:

答案 0 :(得分:2)

将步骤分解为离散函数,

// Inner observable, calls the API
const callAction$ = function(someParameters) {
  return Observable.fromPromise(
    myHttpApi.someActionCall(someParameters)
  ) 
}

// Outer observable, controls the click chain
const click$ = new Subject();
click$.switchMap(clickParams => {
  return callAction$(clickParams)
})
.subscribe(
  result => console.log('Result: ', result), 
  err => console.log('Error: ', err.message)
)

// Handler function, called from menu
const handleClick = function(clickParams) {
  click$.next(clickParams)
}

工作示例CodePen

相关问题