crimx/observable-hooks

如何使用 useObservableEagerState 获取“从无到有”的 BehaviorSubject 值?

Fiv5 opened this issue · 2 comments

Fiv5 commented

示例代码:

const queryService = graphStoreGet.queryService();

const krResult$ = useObservable(
    input$ =>
      queryService.okrSubjectMap$.pipe(
        withLatestFrom(input$),
        filter(([okrSubjectMap, [kdId]]) => Boolean(okrSubjectMap[kdId])),
        switchMap(([okrSubjectMap, [kdId]]) => okrSubjectMap[kdId]),
      ),
    [krItem.item.id],
);
const krResult = useObservableEagerState(krResult$);

okrSubjectMap 初始是一个空对象,类型是 Record<string, BehaviorSubject>,会动态的往里添加值,因此初始调用时会报错: Error: Observable did not synchronously emit a value.

crimx commented

那你这里不需要 Eager,因为 Eager 是为了从 Observable 中获取初始值,你这里很明显是不能保证 krResult$ 有静态初始值的,这里可以改为用 useObservableState 并提供初始值。 const krResult = useObservableState(krResult$, 'defaultValue');

Fiv5 commented

感谢,已经用 useObservableState 解决了