Home > Net >  Confusion on caveats of using lastValueFrom
Confusion on caveats of using lastValueFrom

Time:10-19

RXjs lastValueFrom documentation states:

WARNING: Only use this with observables you know will complete. If the source observable does not complete, you will end up with a promise that is hung up, and potentially all of the state of an async function hanging out in memory.

Does this mean "know will EMIT complete", or "know will end at some point by either emitting complete or error?" This is causing confusion on our team because HTTPclient sometimes emits error instead of complete, and we can not determine from documentation if this will cause the promise to 'hang up and hang out in memory."

CodePudding user response:

Consider

lastValueFrom(interval(1000))

This will return a promise that will never resolve. This is what they're talking about. Errors won't be a problem.

So the answer to your question is "know will end at some point by either emitting complete or error"... except I don't know that it makes sense to say "emit complete". EMPTY, for example, is an observable that completes, but it doesn't emit anything.

CodePudding user response:

In the docs:

Check out the line right before the warning:

If the observable stream emits an error, the returned promise will reject with that error.

At this point you needn't worry about RxJS anymore, you can look into how promises work. A promise that has rejected or resolved is a promise that is decisively not hung up. A promise resolves or rejects exactly once and thereafter doesn't pollute the JavaScript event loop.

That being said, perhaps the warning in the RxJS docs is a bit poorly worded.

CodePudding user response:

An observable that throws an error doesn't complete.

So lastValueFrom will also emit an error.

For example :

function foo(): Promise<void> {
  return lastValueFrom(
    of().pipe(switchMap(() => throwError(() => new Error('test'))))
  );
}

async function bar(): Promise<void> {
  try {
    console.log(await foo()); // won't log
  } catch (e) {
    console.log(e); // logs the error
  }
}

bar();
  • Related