Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion stream-helpers/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@effectionx/stream-helpers",
"description": "Type-safe stream operators like filter, map, reduce, and forEach",
"version": "0.7.3",
"version": "0.8.0",
"type": "module",
"main": "./dist/mod.js",
"types": "./dist/mod.d.ts",
Expand Down
25 changes: 25 additions & 0 deletions stream-helpers/subject.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,31 @@ describe("subject", () => {
expect(yield* next(subscriber2)).toEqual("bye");
});

it("yields initial value to first subscriber before any upstream values", function* () {
subject = createSubject(42);
downstream = subject(upstream);

const subscriber = yield* downstream;
expect(yield* next(subscriber)).toEqual(42);

yield* upstream.send(1);
expect(yield* next(subscriber)).toEqual(1);
});

it("yields upstream value to late subscriber once upstream has sent", function* () {
subject = createSubject(42);
downstream = subject(upstream);

const subscriber1 = yield* downstream;
expect(yield* next(subscriber1)).toEqual(42);

yield* upstream.send(1);
expect(yield* next(subscriber1)).toEqual(1);

const subscriber2 = yield* downstream;
expect(yield* next(subscriber2)).toEqual(1);
});

it("subscriber after close receives last value and close value", function* () {
const subscriber1 = yield* downstream;

Expand Down
27 changes: 16 additions & 11 deletions stream-helpers/subject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,28 +35,33 @@ import type { Stream, Subscription } from "effection";
* ]);
* ```
*/
export function createSubject<T>(): <TClose>(
stream: Stream<T, TClose>,
) => Stream<T, TClose> {
let current: IteratorResult<T> | undefined = undefined;
export function createSubject<T>(
initial?: T,
): <TClose>(stream: Stream<T, TClose>) => Stream<T, TClose> {
let current: IteratorResult<T> | undefined =
typeof initial !== "undefined"
? { done: false, value: initial }
: undefined;

return <TClose>(stream: Stream<T, TClose>) => ({
*[Symbol.iterator]() {
let upstream = yield* stream;

let tracking: Subscription<T, TClose> = {
*next() {
current = yield* upstream.next();
return current;
},
};

let iterator: Subscription<T, TClose> = current
? {
*next() {
iterator = upstream;
iterator = tracking;
return current!;
},
}
: {
*next() {
current = yield* upstream.next();
return current;
},
};
: tracking;

return {
next: () => iterator.next(),
Expand Down
Loading