Confused Mind: Either I'm mistaken, or the whiskey is starting to take effect. (I can't rule out the possibility that I'm just going crazy. Apologies for that.)
Assumption:
My assumption was that ReplaySubject would emit a single value every 2 seconds because I wait two seconds before calling next()
each time.
Outcome:
However, all values are actually output simultaneously after waiting for 2 seconds.
The problematic code snippet is as follows:
import { ReplaySubject } from 'rxjs';
export const rs$: ReplaySubject<number> = new ReplaySubject();
rs$.subscribe({
next: (data) => console.log(data),
error: (error) => console.warn(error),
complete: () => console.log('ReplaySubject completed'),
});
const fakeAPIValuesOne: Array<number> = [7, 11, 13];
fakeAPIValuesOne.forEach(async (entry: number) => {
await wait(2000); // <--- Why does wait() not work?
rs$.next(entry);
});
function wait(milliseconds: number) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
Query:
What am I fundamentally misunderstanding in this scenario?
If you want to test it yourself: https://stackblitz.com/edit/rxjs-wpnqvq?file=index.ts
UPDATE 1:
Using setTimeout also doesn't seem to make any difference. The following modified code results in the same behavior as before:
fakeAPIValuesOne.forEach((value: number) => {
setTimeout(() => {
rs$.next(value);
}, 2000);
});
I'm puzzled by how next()
manages to override all the delays here?
UPDATE 2
The issue has been resolved, correct answer identified, thank you! You need this setup to enable root level awaits for your ts-files.
package.json
Please pay attention to the type section:
{
"name": "playground",
"version": "1.0.0",
"description": "",
"main": "index.ts",
"scripts": {
"start": "nodemon index.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"rxjs": "^7.5.5",
"ts-node": "^10.7.0",
"typescript": "^4.8.0-dev.20220507"
},
"type": "module"
}
nodemon.json
Please use the following configuration to avoid the error:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"
{
"execMap": {
"ts": "node --loader ts-node/esm"
}
}
Lastly, update your tsconfig.json
{
"compilerOptions": {
"module": "ESNext",
"target": "ESNext",
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"isolatedModules": true,
"noEmit": true,
"strict": true,
"lib": ["esnext", "DOM"]
}
}