Hal*_*alt 10 design-patterns void observable rxjs typescript
当异步服务没有返回值但我想使用Observables我倾向于使用Observable<boolean>.但我对这个布尔值没有意义,因为服务失败或成功,如果失败,我希望Observable处于错误状态.这只为观察到的布尔值留下了"真实"值.
以下是Observable<void>针对这些情况使用的好模式吗?或者是否存在可预见的使用问题Observable<void>
const asyncFuncWithoutResult = (): Observable<void> => {
// fake something async that has no return value
const itWorked = true; // or not
if (itWorked) {
return Observable.of();
} else {
return Observable.throw(Error('It did not work'));
}
}
// call the service
asyncFuncWithoutResult()
.subscribe(
undefined, // nothing will be emitted when using Observable.of()
(err: any) => console.error(err), // handle error state
() => console.log('Success'), // handle success state
);
Run Code Online (Sandbox Code Playgroud)
mar*_*tin 11
更准确地说,当您使用泛型类型定义Subject时,void有两种方法可以调用其next()方法,而且没有任何参数:
const subject = new Subject<void>();
subject.next();
Run Code Online (Sandbox Code Playgroud)
......或者void 0:
subject.next(void 0);
Run Code Online (Sandbox Code Playgroud)
事实上,value参数next是可选的,所以如果你没有指定它,它将发送undefined,这意味着即使Subject<void> 你仍然会收到next通知:
asyncFuncWithoutResult().subscribe(alawaysUndefined => {
/* ... */
});
Run Code Online (Sandbox Code Playgroud)
另请注意,您可以<void>通过map或将任何Observable转换为(当您想要合并多个Observable时这是必要的)mapTo:
source.mapTo(void 0)
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5036 次 |
| 最近记录: |