Repository navigation
Expand file tree
/
Copy pathrx.html
More file actions
91 lines (78 loc) · 2.9 KB
/
Copy pathrx.html
File metadata and controls
91 lines (78 loc) · 2.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Weather Monitoring in RxJS</title>
<style>
#form {
margin-bottom: 20px;
}
.location {
float: left;
padding: 10px;
margin-right: 20px;
margin-bottom: 20px;
border: 1px solid #ddd;
border-radius: 5px;
}
.location p {
margin-top: 10px;
margin-bottom: 10px;
text-align: center;
}
.zip { font-size: 2em; }
.temp { font-size: 4em; }
</style>
</head>
<body>
<div id="app-container">
<div id="form">
<label>Zip Code:</label>
<input type="text" id="zipcode-input">
<button id="add-location">Add Location</button>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.all.min.js"></script>
<script>
// Grab HTML elements
const appContainer = document.getElementById('app-container');
const zipcodeInput = document.getElementById('zipcode-input');
const addLocationBtn = document.getElementById('add-location');
//Adding Button click stream
const btnClickStream = Rx.Observable
.fromEvent(addLocationBtn, 'click')
.map(() => true);
//Adding Zip code stream
const zipCodeInputStream = Rx.Observable
.fromEvent(zipcodeInput, 'input')
.map(e => e.target.value)
.filter(zip => zip.length === 5 || zip.length === 6);
//Resulting stream
const zipCodeStream = btnClickStream
.withLatestFrom(zipCodeInputStream, (click, zip) => zip)
.distinct();
//Get temperature
const getTemperature = zip => fetch(`http://api.openweathermap.org/data/2.5/weather?q=${zip},us&units=metric&appid=a428bc9d72a70f4ea1df9fc2746dfb9f`)
.then(res => res.json());
const zipTemperatureStreamFactory = zip => Rx.Observable.fromPromise(getTemperature(zip))
.map( ({main: {temp} }) => ({temp, zip}) ); //Destructure the result
zipCodeStream
.flatMap(zipTemperatureStreamFactory)//works just like map, but subscribes to each observable returned and returns its value
.forEach( ({zip, temp}) => {
const locationEle = document.createElement('div');
const locationId = `zip-${zip}`;
locationEle.classList.add('location');
const zipEle = document.createElement('p');
zipEle.classList.add('zip');
zipEle.innerText = zip;
const tempEle = document.createElement('p');
tempEle.classList.add('temp');
tempEle.innerHTML = `${temp}°C`;
locationEle.appendChild(zipEle);
locationEle.appendChild(tempEle);
appContainer.appendChild(locationEle);
zipcodeInput.value = '';
});
</script>
</body>
</html>