【发布时间】:2020-07-16 22:46:02
【问题描述】:
我想根据两个条件停止可观察订阅:
- 时间(使用
import { timer } from 'rxjs/internal/observable/timer';)
或
- 执行状态(使用请求中返回的对象,您将在下面看到)
发生了什么:
它只是根据时间停止执行(使用import { timer } from 'rxjs/internal/observable/timer';)
这是我当前的代码:
出于示例目的,属性、变量及其值的名称已更改:
import { finalize } from 'rxjs/internal/operators/finalize';
import { interval } from 'rxjs/internal/observable/interval';
import { timer } from 'rxjs/internal/observable/timer';
import { takeUntil, first } from 'rxjs/operators';
import { merge, EMPTY, of } from 'rxjs';
.
. // Attributes and Class declaration here
.
async startProcess(): Promise<void> {
this.isProcessLoading = true;
const { someId } = await this.exampleService.execute().toPromise();
const interval$ = interval(1000);
const timeLimiter$ = timer(10000);
const request$ = this.exampleService.doRequest();
const isEventFinished$ = EMPTY;
// My goal here is for the result of this function to return an observable that notifies
// if the first parameter emits an event OR if the second parameter emits another. That is, I want to notify if any condition is valid
const stopConditions$ = merge(isEventFinished$, timeLimiter$);
const handleSuccess = (object: MyType) => {
if (object.status === 'FINALIZED') {
this.object = object;
isEventFinished$.subscribe();
}
};
const handleError = () => this.showErrorComponent = true;
interval$
.pipe(takeUntil(stopConditions$))
.pipe(finalize(() => this.isSimulationLoading = false))
.subscribe(() => request$.subscribe(handleSuccess, handleError));
}
代码“有效”是因为 timeLimiter$ 在 10 秒后触发 takeUntil。但是,我希望有可能在时间限制之前停止......
我希望 takeUntil 也能从这里运行:
isEventFinished$.subscribe()
如果上面的sn-p正确执行,应该停止interval$,但它没有。那是我的问题
我已经尝试过的:
-
我不知道两个管道是否比只使用一个这样的管道有什么不同:
.pipe(takeUntil(stopConditions$), finalize(() => this.isSimulationLoading = false))。但是,我已经尝试过了,但没有成功 -
已尝试将
isEventFinished$替换为:const isEventFinished$ = of(1)和他的订阅:timeLimiter$.pipe(first()).subscribe()。 但这也不起作用。实际上,这会阻止请求被执行(我不知道为什么)
【问题讨论】:
-
您可能会遇到从
rxjs/internal/operators/而不是简单的rxjs/operators导入的问题。我知道我的 IDE 已经咬了我几次从/internal自动导入。 -
还是不行。我的
merge运算符或isEventFinished$有问题
标签: javascript angular rxjs rxjs6