Combine Latest exercices

Example of combine latest of 2 input observables that make an http request to get an image url

by Mario_Rivis

HTML

<script src="https://unpkg.com/@reactivex/[email protected]/dist/global/Rx.js"></script>

<input id="my-input" type="number">
 Thumbnail
 <input id="my-checkbox" type="checkbox"/>
 
 <hr>
  
 <img id="my-img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTrZIbr3gK43A2R2jgOV2HUrCkbdNPdt0nYRM2HweWezVDsMyHz&s"/>

JavaScript

const myInput = document.getElementById('my-input');
const myCheckbox = document.querySelector('#my-checkbox');

const photoId$ = Rx.Observable.fromEvent(myInput, 'input')
    .debounceTime(300)
    .map(event => event.target.value)
    .filter(id => id && id !== '')
    .filter(id => id > 0 && id <= 5000);

const thumbnail$ = Rx.Observable.fromEvent(myCheckbox, 'input')
    .map(event => event.target.checked);
  
  
  
const subscription = Rx.Observable.combineLatest(photoId$, thumbnail$)
     .switchMap(values => {
     [id, isThumbnail] = values;
     return Rx.Observable
              .ajax('https://jsonplaceholder.typicode.com/photos/'+id)
              .map(ajaxRes => ajaxRes.response)
              .map(res => {
              	return isThumbnail? res.thumbnailUrl: res.url;
              })
     })
    .subscribe(
       url => document.getElementById("my-img").src = url,
       err => console.log(err),
       complete => console.log('complete'));