Rodrigo Martinez
Rodrigo Martinez

Reputation: 943

Return an observable after a couple of actions have been performed

I need to perform some actions (which I don't know beforehand) and after all of them are done I would like to return a void observable for someone interested may be listening to in order to do something else once this is finished.

Sample:

Class A

public hook: () => void;

pubic doAndReturnObservable(): Observable<void>{
    hook();
    return Observable.of();
}

public notifyToOther(){
    classB.notify(this.doAndReturnObservable());
}

hook is an arrow function that is being passed to class A and will include several things that would like to be performed in a generic way

Class B

public notify(actionsToPerform: Observable<void>){
    actionsToPerform.subscribe(()=>{
       console.log('now all has been done! I can do something else');
    });
}

The thing is that I don't know what 'hook' might do, there may be several actions and they could include http calls or async processes. My doAndReturnObservable method will trigger the hook with all that needs to be done but it wont wait for it to finish before returning the observable I'm then subscribing to, so my console log is being shown before the hook is done.

Does someone has a way for achieving this kind of things? Thanks in advance.

Upvotes: 0

Views: 239

Answers (1)

Prashant M Bhavsar
Prashant M Bhavsar

Reputation: 1164

Check this:

async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // wait till the promise resolves (*)

  alert(result); // "done!"
}

Here promise will wait to complete Promise to resolve. Ref to https://javascript.info/async-await

Upvotes: 1

Related Questions