W
W
waltaki2019-08-08 13:02:59
JavaScript
waltaki, 2019-08-08 13:02:59

Rxjs - how to double subscribe?

Hello.
Please tell me how to implement this:

let get = () => {
    return this.http.get(url)
        .subscribe((responce: ResponceObject) => {...});
}

get()
    .subscribe((responce: ResponceObject) => {...});

Need it in service. I already implemented it with regular callbacks, but still, suddenly there is something better in this case. flatmap could not understand. Tell me, please, in which direction to look or not to look.
It is desirable, of course, with a code example))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Demian Smith, 2019-08-08
@waltaki

The observer doesn't do any work until the subscribe function has been called. The process of calling subscribe is called "subscribing". As soon as the subscribe function was called (i.e., the observer was subscribed), the matter went and the observer began its work. Until subscribe is called, the observer is just a recipe for what to do when data arrives.
The subscribe function itself returns a destructor. The destructor is something that needs to be executed if suddenly it was necessary to stop the observer (for example, to interrupt the HttpConnection).
The code below returns a destructor function

let get = () => {
    return this.http.get(url)
        .subscribe((response: ResponseObject) => {...});
}

The destructor function cannot be subscribed to. She also has no callbacks. It can only be executed in order to stop the browser.
Therefore, the universal recipe is never to subscribe in the services themselves. If you need to do something with the data from the browser in the service itself, then you can use the tap operator:
let get = () => {
    return this.http.get(url)
        .pipe(
          tap((response: ResponseObject) => {...})
        );
}

// а дальше где-то в коде сделать

service.get().subscribe((response: ResponseObject) => {...})

Moreover, you can do tap (and any other pipe statement) as long as you have an observable:
service.get()
  .pipe(
    tap(...),
    map(...),
    whatever(...),
  ).subscribe((response: ResponseObject) => {...})

It will be easier for you to understand how observables work if you think of observable as a function and the subscribe method as a way to execute that function.
In light of the above:
const observable = service.get();
observable.subscribe((result) => {...}); //выполнит запрос к серверу
observable.subscribe((result) => {...}); //выполнит запрос к серверу еще раз
// запрос к серверу будет инициироваться каждый раз когда будет выполняться функция subscribe

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question