title: RxJS BehaviorSubject cashing request from http call
body: <p>I'm having hard time finding neet solution for cashing http request to BehaviorSubject. I wanted to have only single method for cashing and getting value. Example below:</p>
  
  <pre><code>@Injectable({
    providedIn: 'root'
  })
  export class DataStoreService {
  
    private readonly initialState: DataState = {
      data: string,
      loaded: false
    };
  
    private data$: BehaviorSubject&lt;DataState&gt; = new BehaviorSubject&lt;DataState&gt;(this.initialState);
  
    constructor(private dataService: DataService) { }
  
    getData$(id: string): Observable&lt;string&gt; {
      return this.data$.asObservable()
        .pipe(
          switchMap((state: DataState) =&gt; {
            if (!state.loaded) {
              this.dataService.getData$(id);
            } else {
              return of(state.data);
            }
          }),
          withLatestFrom(this.data$.asObservable()),
          map(([data, state]) =&gt; {
            if (!state.loaded) {
              this.data$.next({
                loaded: true,
                data
              });
            }
            return data;
          })
        );
    }
  }
  </code></pre>
  
  <p>I haven't tested it yet (service not working), but looks ok for now. Anybody knows any better solution to have less piping and conditionals (if/else) in rxjs for this kind of usage?</p>