Good Observable Exercise
Exercise template for Observables
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
/*
* You have two input fields: my-input, which is of type number and my-checkbox, which returns a boolean.
* The number represents the id of the photo you want to get (a number between 1 and 5000)
* The checkbox tells us wether to render the url of the image or it's thumbnail in the image "#my-img"
*
* For more details visit https://jsonplaceholder.typicode.com/
* Response example: https://jsonplaceholder.typicode.com/photos/40
*
* When either one of the input changes, create an http request to get the image from the jsonplaceholder site.
* If he thumbnail checkbox is active, render the thumbnailUrl, else the url field.
*
* HINT: to get the value of the checkbox map the event -> event.target.checked
*/
const defaultImage = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTrZIbr3gK43A2R2jgOV2HUrCkbdNPdt0nYRM2HweWezVDsMyHz&s";
const myInput = document.getElementById('my-input');
const myCheckbox = document.querySelector('#my-checkbox');
const photoId$ = Rx.Observable.fromEvent(myInput, 'input');
const thumbnail$ = Rx.Observable.fromEvent(myCheckbox, 'input');
const subscription = Rx.Observable.combineLatest(photoId$, thumbnail$)
.switchMap(values => {
[id, isThumbnail] = values;
return Rx.Observable.of(defaultImage);
})
.subscribe(
url => document.getElementById("my-img").src = url,
err => console.log(err),
complete => console.log('complete'));