【问题标题】:Rxjs Subscribing until another event happensRxjs 订阅直到另一个事件发生
【发布时间】:2017-10-27 00:42:00
【问题描述】:

我是 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;
                    }
                });
            };
    

观察者进一步定义如下:

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,从而结束对第一个请求的订阅并订阅新请求(在此示例中,为不同的菜单选项执行相同的代码块,因此基于不同的请求参数上)是否启动?

【问题讨论】:

标签: rxjs


【解决方案1】:

将步骤分解为离散函数,

// 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多