SwitchMap Example
Example of how switchmap works
by Mario_Rivis
HTML
<script src="https://unpkg.com/@reactivex/[email protected]/dist/global/Rx.js"></script>
<input id="my-input" type="number">
<hr>
<img id="my-img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTrZIbr3gK43A2R2jgOV2HUrCkbdNPdt0nYRM2HweWezVDsMyHz&s"/>
JavaScript
const myInput = document.getElementById('my-input');
Rx.Observable.fromEvent(myInput, 'input')
/* .debounceTime(300) */
.map(event => event.target.value)
.filter(id => id && id !== '')
.filter(id => id > 0 && id <=5000)
/* .flatMap(id => */
.switchMap(id =>
Rx.Observable
.ajax('https://jsonplaceholder.typicode.com/photos/'+id)
.map(ajaxRes => ajaxRes.response.url)
)
.subscribe(
url => document.getElementById("my-img").src = url,
err => console.log(err),
() => console.log('complete'));