'How do I run code after returned function subscription?

I have the following code that looks like this:

foo(){
   return this.service.asyncFunction();
}

//in another function:

this.foo().subscribe(() => { some_code });

Is it possible to refactor the foo function too look like this:

foo(){
   return this.service.asyncFunction().subscribe();
}

But still be able to run some_code after the subscription?



Solution 1:[1]

If you want to subscribe inside foo() and still be able to send the observable you can do this

foo(){
   const myObs = this.service.asyncFunction();
   myObs.subscribe();
   return myObs;
}

Somewhere else in the code, you can do this

this.foo().subscribe(() => { some_code });

But if you want to use foo() and give it some code then you can do this

foo(callback){
   this.service.asyncFunction().subscribe(callback);
}

And somewhere else in the code, do this

for(() => { some code });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1