Skip to content

Instantly share code, notes, and snippets.

@ayoung4
Created April 29, 2021 19:23
Show Gist options
  • Save ayoung4/e092f1c1a0454f56e72c9c6c7aebcf70 to your computer and use it in GitHub Desktop.
Save ayoung4/e092f1c1a0454f56e72c9c6c7aebcf70 to your computer and use it in GitHub Desktop.
trying to understand how to run an effect in the background, provided as a layer to another program
import * as F from '@effect-ts/core/Effect/Fiber'
import * as L from '@effect-ts/core/Effect/Layer'
import * as M from '@effect-ts/core/Effect/Managed'
import * as T from '@effect-ts/core/Effect'
import { pipe } from '@effect-ts/core/Function'
import { tag } from '@effect-ts/core/Has'
import { testRuntime } from '@effect-ts/jest/Runtime'
describe('run an effect forever in the background and stop when the test is done', () => {
const log: string[] = []
interface LogForeverFiber {
fiber: F.Fiber<never, never>
}
const LogForeverFiber = tag<LogForeverFiber>()
// in real application this would drain a queue
const logForever = pipe(
T.succeedWith(() => {
log.push('log')
}),
T.delay(400),
T.forever,
)
// fork logForever into a new fiber when program starts,
// interrupt the fiber when the program ends
const LogForeverFiberLive = pipe(
logForever,
T.fork,
M.makeInterruptible(F.interrupt),
M.map((fiber): LogForeverFiber => ({ fiber })),
L.fromManaged(LogForeverFiber)
)
const { it } = testRuntime(LogForeverFiberLive)
// fails, log is empty
it('works', () => T.gen(function* (_) {
yield* _(T.delay(2000)(T.unit))
expect(log).toEqual([
'log',
'log',
'log',
'log',
'log',
])
}))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment