Effect CommunityEC
Effect Community3y ago
13 replies
Jérôme MARTIN

Comparing the Benefit of Using Ref vs Mutable Array

Hi there. I am trying to understand the benefit of using Ref. So I tried the example in the doc and, ok, it works perfectly. Then, I just replaced Ref by a normal mutable array. And I get the very same result:
import { Effect, Fiber } from 'effect';
import * as NodeReadLine from 'node:readline';

const readLine = (message: string): Effect.Effect<never, never, string> =>
    Effect.promise(
        () =>
            new Promise((resolve) => {
                const rl = NodeReadLine.createInterface({
                    input: process.stdin,
                    output: process.stdout
                });
                rl.question(message, (answer) => {
                    rl.close();
                    resolve(answer);
                });
            })
    );
// $ExpectType Effect<never, never, Chunk<string>>
const getNames = Effect.gen(function* (_) {
    const state: string[] = [];

    const fiber1 = yield* _(
        Effect.fork(
            Effect.gen(function* (_) {
                while (true) {
                    const name = yield* _(
                        readLine('Please enter a name or `q` to exit: ')
                    );
                    if (name === 'q') {
                        break;
                    }
                    state.push(name);
                }
            })
        )
    );
    const fiber2 = yield* _(
        Effect.fork(
            Effect.gen(function* (_) {
                for (const name of ['John', 'Jane', 'Joe', 'Tom']) {
                    state.push(name);
                    yield* _(Effect.sleep('1 seconds'));
                }
            })
        )
    );
    yield* _(Fiber.join(fiber1));
    yield* _(Fiber.join(fiber2));
    return state;
});

const result = await Effect.runPromise(getNames);
console.log(result);

So the benefit of Ref does not clearly occur to me. There must be something about Refs being effectful. But I don't manage to see where that matters.
Was this page helpful?