kinda fixed?

This commit is contained in:
Víctor Oliva 2023-09-19 11:43:57 +02:00
parent 599f8d2ab2
commit 6cf255eed8
2 changed files with 32 additions and 9 deletions

View File

@ -2,7 +2,7 @@ import { Subject } from "rxjs"
import { describe, expect, it } from "vitest"
import { createRoot } from "./create-root"
import { substate } from "./substate"
import { subtree } from "./subtree"
import { activeObs$, subtree } from "./subtree"
describe("subtree", () => {
it("creates instances of another root", () => {
@ -28,7 +28,7 @@ describe("subtree", () => {
const subnode$ = new Subject<string>()
const subnode = substate(mainRoot, () => subnode$)
const otherRootCopy = substate(subnode, (_, getObs$) => getObs$(otherRoot))
const otherRootCopy = substate(subnode, () => activeObs$(otherRoot))
const otherRoot = createRoot().withTypes<{ value: string }>()
subtree(subnode, (ctx) => otherRoot.run(null, { value: ctx(subnode) }))

View File

@ -1,10 +1,5 @@
import { Observable } from "rxjs"
import {
NestedMap,
createStateNode,
getInternals,
trackParentChanges,
} from "./internal"
import { Observable, defer, filter, switchMap, take } from "rxjs"
import { NestedMap, getInternals, trackParentChanges } from "./internal"
import {
GetObservableFn,
GetValueFn,
@ -57,3 +52,31 @@ export function subtree<K extends KeysBaseType>(
onRemoved: teardown,
})
}
export function activeObs$<T>(node: StateNode<T, {}>): Observable<T>
export function activeObs$<T, K extends KeysBaseType>(
node: StateNode<T, K>,
key: K,
): Observable<T>
export function activeObs$<T, K extends KeysBaseType>(
node: StateNode<T, K>,
key: K = {} as any,
): Observable<T> {
const internalNode = getInternals(node)
return defer(() => {
try {
return internalNode.getInstance(key).getState$()
} catch (ex) {
return internalNode.instanceChange$.pipe(
filter(
(change) =>
change.type === "ready" &&
internalNode.keysOrder.every((k) => change.key[k] === key[k]),
),
take(1),
switchMap(() => node.getState$(key)),
)
}
})
}