Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular/RxJS: synchronous observable

Tags:

angular

rxjs

I have a service that has a method foo. Inside the method I subscribe to an observable (http-client).

foo () : boolean
{
  let ret : false;

  this.http.get ("/blabla").subscribe (
  (resp) =>
  {
    ret = true;
  }

  return ret;
);

I like to return a boolean value from foo that depends on the get. That is not working because http.get is asynchrouns - return is called before http.get finished.

How can I make this synchronous?

EDIT

Returning the observable instead boolean is not an option here. That is because I handle the response of get in foo (not shown here) but I also need to act out of foo depending of its return.

EDIT2

I extended my sample with pipe and tap. Now I return the http.get-observable for outside the service and I process the http.get-result with tap.

foo () : Observable <any>
{
  return this.http.get ("/blabla").pipe (tap (x => handlehere ()));
}

As far I see there is only one uglyness with it. I have the complexity of parsing the get-result inside AND outside of foo. I would prefer a simple boolean outside of foo.

like image 484
chris01 Avatar asked Sep 24 '18 18:09

chris01


People also ask

Can Observable be synchronous?

A common misconception in Angular development is regarding whether observables are synchronous or asynchronous. A lot of (even experienced Angular developers) think that observables are async, but the truth is that they can be… Both synchronous and asynchronous.

Is Observable sync or async?

An observable produces values over time. An array is created as a static set of values. In a sense, observables are asynchronous where arrays are synchronous.

Is Angular Observable async?

Angular makes use of observables as an interface to handle a variety of common asynchronous operations. For example: The HTTP module uses observables to handle AJAX requests and responses. The Router and Forms modules use observables to listen for and respond to user-input events.

What is synchronous and asynchronous in Angular?

In synchronous operations tasks are performed one at a time and only when one is completed, the following is unblocked. In other words, you need to wait for a task to finish to move to the next one. In asynchronous operations, on the other hand, you can move to another task before the previous one finishes.


1 Answers

This method can only run asynchronously so you don't have a lot of option. Returning the obsersable and subscribe or return a promise. Perhaps returning a Promise will suite more your need in term of comprehention.

In your service : the foo method :

async foo() {
   const result = await this.http.get("/blabla").toPromise();

   // do what you want with result 

   return result;
}

How to call it :

this.myService.foo().then( (result) => {
   // Do what you want with the result
});
like image 196
xrobert35 Avatar answered Oct 08 '22 07:10

xrobert35