Is http response one element in Observable (Rxjs) stream?

Viewed 478

I am currently expanding my knowledge of RxJs and trying to get better understanding of streams. I would like to compare Http response to an Observable made by of().

Can we say that JSON response is treated like element 'a' when comparing it to of(['a', 'b', 'c']) ? When we get JSON response it's always like getting only one element?

Is http response one element in Observable stream?

EDIT: Obviously, I should have compared it to the first emitted value of interval().

1 Answers

An HTTP request using Angular HTTP client is in-fact an RxJS observable of type HttpRequest that produces a stream of notifications of type HttpEvent. If you wish to see all the notifications, use the option observe: 'events' in the request. If this option isn't provided (default), only the last notification (the result from the HTTP request) is returned as seen here.

From docs:

When using HttpClient.request() with an HTTP method, configure the method with observe: 'events' to see all events, including the progress of transfers.

Seeing this, your example of of(['a', 'b', 'c']) isn't similar to a HTTP request since it emits only one notification (the array ['a', 'b', 'c']) and completes. However from(['a', 'b', 'c']) is similar to a HTTP request since it emits each item individually.

Is HTTP response one element in Observable stream?

Yes, it is the last notification in the stream of notifications. It is of type HttpEventType.Response.

Working example: Stackblitz

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpEvent, HttpEventType } from '@angular/common/http';

@Component({ selector: 'app', templateUrl: 'app.component.html' })
export class AppComponent implements OnInit {
  events = [];

  constructor(private http: HttpClient) { }

  ngOnInit() {      
    this.http.get<any>('https://jsonplaceholder.typicode.com/todos/1', {observe: 'events'}).subscribe((event: HttpEvent<any>) => {
      this.events.push(event);
      console.log(event);
    });
  }
}

Console output enter image description here

type: 0 corresponds to HttpEventType.Sent and type: 4 corresponds to HttpEventType.Response. You could possibly see more events in a more complicated request (eg. a video upload request).

Related