Skip to content

Instantly share code, notes, and snippets.

@lxchurbakov
Last active July 12, 2020 11:42
Show Gist options
  • Save lxchurbakov/4d6d0e9747c1d1b7d44047a2d95c6e80 to your computer and use it in GitHub Desktop.
Save lxchurbakov/4d6d0e9747c1d1b7d44047a2d95c6e80 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.0/rxjs.umd.js"></script>
</head>
<body>
<input id="name" />
<div id="gender">Gender: null</div>
<script>
const { mergeMap, map } = rxjs.operators
const nameSubject = new rxjs.Subject()
const genderSubject = new rxjs.Subject()
const input = document.getElementById('name')
const gender = document.getElementById('gender')
/* Put name from input to nameSubject */
rxjs.fromEvent(input, 'input').pipe(map((e) => e.target.value)).subscribe(nameSubject)
/* Get gender and put it to genderSubject */
nameSubject.pipe(mergeMap((name) => new rxjs.Observable((observer) => {
fetch(`https://api.genderize.io?name=${name}`).then(async (res) => {
observer.next((await res.json()).gender)
observer.complete()
}).catch((err) => {
observer.error(err)
})
}))).subscribe(genderSubject)
/* Map genderSubject to div */
genderSubject.subscribe({
next: (value) => gender.innerText = `Gender: ${value}`,
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment