Making first observable in chain optional

Making first observable in chain optional



I currently have two API requests, where the first feeds into the second:


.get('/call1', )
.pipe(
switchMap(response => {
this.api.get('/call2', )



This works fine (though if there's a more appropriate way of doing it, I'd love to hear!). However, with some recent changes to my app, I realize in certain cases I have the data that call1 gets already stored, and thus can go straight to the second call, but I can't figure out how to do that. In other cases, within a switchMap, I've done something like:


call1


switchMap


if (condition)
return this.api.get('/call2');
else
return ObservableOf(cachedData);



How can I do something similar for the first call in a chain?





why not just subscribe ... this.api.get('...').subscribe( (result) => whatever you want)
– Stavm
Aug 22 at 13:44



this.api.get('...').subscribe( (result) => whatever you want)





From everything I've read/seen, it's really bad form to call an observable from within an observable? That's the point of maps.
– RhoVisions
Aug 22 at 15:39




2 Answers
2



You can apply the condition in a separate function


getCall1()
.pipe(
switchMap(response => {
this.api.get('/call2', )



The function can decide where to get the data from and return an observable just like your example:


getCall1() : Observable<any>
if (condition)
return this.api.get('/call2');
else
return of(cachedData);



I'd recommend using some kind of caching layer or data store in your API layer. That way every time you call "this.api.get()" you can return an observable with the appropriate value if it's already been retrieved. We use the latest version of angular and do something similar while saving the values after API calls locally using the browsers local storage.





It does have caching, but in this instance, the data may not be coming from my api, so doesn't work out.
– RhoVisions
Aug 23 at 20:29





I didn't mean caching on the API side, but on the client side similarly to what tom had suggested above.
– HeWhoFreeks
Aug 24 at 0:38





I am caching client side, but the data doesn't always come from the API, thus why I need to pick from different sources.
– RhoVisions
Aug 24 at 18:41






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)