-1

I have an angular service something like this:

saveNewUser(user: User): Observable<boolean> {
  if (!user || !user.password) {
    return of(false);
  }

  return this.http.put(this.saveUrl, user).pipe(map((res: Response) => res.ok));
}

I am attempting a way to return of(false); to return only when the consumer of saveNewUser(...) subscribe to it. In other words, always return cold observable.

Bubba
  • 119
  • 1
  • 9
  • 1
    what is your issue? – Jota.Toledo Oct 08 '18 at 19:01
  • If the consumer calls `let save$ = saveNewUser({password: null});` and sometime later subscribe to it `save$.subscribe(...);` then the response is lost since the returned observable response was not cold. – Bubba Oct 08 '18 at 19:09
  • 1
    `of` returns a cold observable, so I dont know what you mean with *the response is lost*. If you think this is not the case, please add a minimal complete example of your issue – Jota.Toledo Oct 08 '18 at 19:18
  • My bad. I ran with debugger and yes `of` indeed returns cold. Thanks @Jota.Toledo for your time though. – Bubba Oct 08 '18 at 19:32

1 Answers1

1

If I understand your question correctly, you don't want the first part of the method to be evaluated until the user subscribes. So if initially the user object had a null password, then the password was set on that object, and then the observable was subscribed to, you'd want the result to be the result from http.put().

In the example below, the user is wrapped into an observable and the rest of the execution of the pipe won't run until the observable is subscribed to.

saveNewUser(user: User): Observable<boolean> {
  return of(user).pipe(
    switchMap(u => (!u || !u.password) ? of({ ok: false }) : this.http.put(this.saveUrl, u)),
    map(res => res.ok)
  );
}

This is a pretty awkward way of doing things. For one thing this simply won't work if the object passed is initially undefined or the reference on the outside is changed. Much better would be creating on Observable on any changes to the user and piping the rest of the logic or just simply waiting to call saveNewUser() until after the data is set.

Daniel Gimenez
  • 18,530
  • 3
  • 50
  • 70
  • Well honestly that is not my intention to care for object's property change after calling the method and subscribing to it later. I guess it's good use case with your given assumption. Thanks! – Bubba Oct 08 '18 at 20:07