0
votes

I'm facing a random behavior with the flatMap operator and I can't find the reason why. Sometimes it triggers, sometimes it doesn't...

Here is the situation: The user can change the language in my app, so I have a BehaviorSubject on the language (which is triggered by a select list) returned as an observable by its provider. When there's a change I call (via flatMap) a http request to fetch the data in the language selected.

It looks like this:

this.languageProvider.getLang$().flatMap(langCode => {
  return this.http.get(`https://SERVER_URL.net/datas?lang=${langCode}`)
  .map(data => data.json())
})
.subscribe(
  data => {
    // do smth
  },
  err => {
    // do smth
  }
);

The thing is, when I change the language the http call is most often not triggered.

If I add a simple subscribe it always work...

this.languageProvider.getLang$().subscribe(langCode => {
  console.log(langCode);
});

Any idea why I have this issue ?

Here is the languageProvider:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class LanguageProvider {
  private lang$: BehaviorSubject<string>;

  constructor() {
    this.lang$ = new BehaviorSubject('en');
  }

  setLang(langCode: string) {
    this.lang$.next(langCode);
  }

  getLang$(): Observable<string> {
    return this.lang$.asObservable();
  }
}

Thanks a lot

1

1 Answers

1
votes

OK, fixed it.

It wasn't random actually...

In my (simplified) snippet I didn't write how I handled the server response. Actually I could receive a 304 STATUS CODE if I tried to fetch datas that have not changed on the server (I'm doing this to avoid downloading server datas each time a user starts the app)

THE THING IS, I had to handle the 304 in the error callback since angular takes everything above 299 as an error.

WHAT I DIDN'T KNOW was that the error callback was killing my observable. So the pseudo "random" behavior was actually: - If I tried to reload the app without changing the language, then I got a 304, so the observable was killed - If I tried reload the app after changing the language, then the app would fetch the data for this language and get a 200. So the obserbavle would keep on working

Maybe this will help someone. Cheers