crimx / observable-hooks

⚛️☯️💪 React hooks for RxJS Observables. Concurrent mode safe.
https://observable-hooks.js.org
MIT License
1.03k stars 44 forks source link

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

Closed Fiv5 closed 1 year ago

Fiv5 commented 1 year ago

示例代码:

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 1 year ago

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

Fiv5 commented 1 year ago

感谢,已经用 useObservableState 解决了