Akkusativobjekt Akkusativobjekt -4 years ago 262
TypeScript Question

How to drop the response of an Observable

With the help of Observable.timer(0, 1000) I am making continuous requests to my server in a defined time pattern. After I processed the content of the response it is possible under special conditions and depending on the previous response that I need to drop the response and therefore do not pass it to the subscriber of the service:

export class LoggerService {
constructor(private http: Http) { }
private apiURL = 'assets/file.json';

getList() {
return Observable.timer(0, 1000)
.concatMap(() => this.http.get(this.apiURL))
private extractData(res: Response) {
var fooot = new Foo();
return fooot;

private handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
return Observable.throw(errMsg);

method is then called from
of a component.
At the moment there are two possible solutions I can think of, buy maybe there is a better/clearer approach to solve this problem:

  1. If I have to drop the response I create a special object which is recognized by the subscriber of
    and then specifically handled. But this solution would be very ugly because the dropped response leaves my service and I need to extra write code outside of the service to handle this case.

  2. I throw an exception when I have to drop the response. Then the exception is caught, recognized (to differ it from other cases) and then dropped without any notice/output. Afterwards the observable is restarted. The advantage of this approach is that the observable which should be dropped to not leave the service, but I do not like the usage of exceptions in this case for the control flow.

I tried both solutions and they are working, but I hope there are some better approaches.

Answer Source

I ended up using distinctUntilChanged to archive my goal:

getList() {
    return Observable.timer(0, 1000)
      .concatMap(() => this.http.get(this.apiURL)
      .distinctUntilChanged(null, x => x.json().info[1].value)

Therefore if the current and last response share the same specific value, the newest response is dropped. I guess my question was not clear enough and I did not mention that the decision to drop a response depends on the previous one.

A downside of this approach is that the response have to be parsed twice, but I guess that cannot be avoided. It would be nice to know if the json approch is faster than a complete string compare of the result (body).

If the decision to drop a response only depends on the current response, I would recommend to use a filter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download