RxJs Subject resolve first emitted value as promise

Viewed 215

Is there a way to get a value that was emitted in a Subject or BehviourSubject by awaiting it with the toPromise() method? I have tried using the first() operator, as well as the take(1) operator and that, did not seem to work as I have expected. Something along the lines with the following would resemble my problem:

async function testSubjectToPromise() {
  const sub = new Subject<string>();
  sub.next("Hello");
  const response = sub.toPromise();
  console.log("Task added");
  const result = await response;
  console.log("Task completed");
}

testSubjectToPromise().finally(() => console.log("Done"));
1 Answers

You should use it in a more logical way:

const sub = new Subject<string>();
async function testSubjectToPromise() {
  console.log("Task added");
  const result = await sub.pipe(first()).toPromise();
  console.log("Task completed");
  return result;
}

testSubjectToPromise().then(x => console.log(x)).finally(() => console.log("Done"));
sub.next("Hello");

You have to use Subject outside of your function, because it triggers value emitter for the subject you used as the return value toPromise(). You're just waiting for outside event after declaring your promise.

If you want use existing value from your subject, just use ReplaySubject. Then your code would look like:

async function testSubjectToPromise() {
  const sub = new ReplaySubject<string>();
  console.log("Task added");
  sub.next("Hello");  
  const result = await sub.pipe(first()).toPromise();
  console.log("Task completed");
  return result;
}

testSubjectToPromise().then(x => console.log(x)).finally(() => console.log("Done"));
Related