首页 > 解决方案 > 将完成添加到永远不会完成的可观察对象

问题描述

我正在尝试使用离子包装器向cordova插件添加一个完成。所以我会在订阅者中完成。所以我得到了一些服务,它是科尔多瓦 plaugin 的离子包装器:

 startListen(){
            return this.someService.startListen().pipe(
                switchMap((response) => {
                    return new Observable(subscriber => {
                        if (response.index !== undefined) {
                            subscriber.next(1);
                        }
                        if (response.errorTitle === Message.NOT_FOUND) {
                            subscriber.error(Message.NOT_FOUND);
                        }
                        if (response.errorTitle === Message.CANCELLED) {
                            console.log('blah blah'); <---### IS PRINTED
                            subscriber.complete();
                        }
                    });
                }),
            );
        }

我在某些组件中调用它:

 startListen(){
            this.someFacade.startListen().subscribe(
                (x) => console.log('next', x),
                (x) => console.log('error', x),
                () => console.log('complete'), <---# NOT PRINNTED
            );

console.log('complete') 永远不会被触发的问题。

怎么了?

标签: cordovarxjscordova-plugins

解决方案


takeWhile操作员做你想做的事:

this.someService.startListen().pipe(
  takeWhile(response => response.errorTitle !== Message.CANCELLED),
  switchMap(response => response.index !== undefined
    ? of(response.index)
    : throwError(response.errorTitle)
  )


推荐阅读