Last active
March 17, 2023 17:01
-
-
Save artalar/b908d2c97120fc5f3e149ac36015778d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { test } from 'uvu' | |
import * as assert from 'uvu/assert' | |
import { createTestCtx } from '@reatom/testing' | |
import { atom } from '@reatom/core' | |
import { sleep } from '@reatom/utils' | |
import { reatomAsync, withAbort } from '@reatom/async' | |
test('safe pooling', async () => { | |
const createTask = reatomAsync(async () => Math.random()) | |
const tasks = new Map<number, number>() | |
const poolTask = reatomAsync(async (ctx, taskId: number) => { | |
await sleep(5) | |
const progress = (tasks.get(taskId) ?? -10) + 10 | |
tasks.set(taskId, progress) | |
return progress | |
}) | |
const progressAtom = atom(0) | |
const search = reatomAsync(async (ctx) => { | |
const taskId = await createTask(ctx) | |
while (true) { | |
const progress = await poolTask(ctx, taskId) | |
progressAtom(ctx, progress) | |
if (progress === 100) return | |
} | |
}).pipe(withAbort({ strategy: 'last-in-win' })) | |
const ctx = createTestCtx() | |
const track = ctx.subscribeTrack(progressAtom) | |
const promise1 = search(ctx) | |
await sleep(15) | |
const promise2 = search(ctx) | |
await Promise.allSettled([promise1, promise2]) | |
assert.is(ctx.get(progressAtom), 100) | |
assert.equal( | |
track.inputs(), | |
[0, 10, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100], | |
) | |
;`👍` //? | |
}) | |
test.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment