Created
July 17, 2024 15:05
-
-
Save skanev/9cff2723625fb8b09e0a877c402161f6 to your computer and use it in GitHub Desktop.
RxJS Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {useEffect, useState} from 'react' | |
import { | |
combineLatest, | |
debounceTime, | |
distinctUntilChanged, | |
filter, | |
from, | |
fromEvent, | |
map, | |
Observable, | |
startWith, | |
Subject, | |
switchMap, | |
} from 'rxjs' | |
import './App.css' | |
// | |
// ap | |
// -> request 1 -> response 1 | |
// app | |
// -> request 2 -> response 2 | |
const subject = new Subject<string>() | |
function query(text: string): Observable<string[] | undefined> { | |
return from( | |
fetch(`http://localhost:4567/results?q=${text}`) | |
.then(x => x.json()) | |
.then(x => x as string[]) | |
).pipe(startWith(undefined)) | |
} | |
function search(text: string): Observable<string[]> { | |
return from( | |
fetch(`http://localhost:4567/results?q=${text}`) | |
.then(x => x.json()) | |
.then(x => x as string[]) | |
) | |
} | |
function App() { | |
const [results, setResults] = useState<string[]>([]) | |
useEffect(() => { | |
const first = query('a') | |
const second = query('app') | |
combineLatest([first, second]).subscribe({ | |
next(value) { | |
console.log(new Date().toTimeString()) | |
console.log(value) | |
}, | |
}) | |
subject.subscribe({ | |
next(value) { | |
console.log(value) | |
}, | |
}) | |
const observable = fromEvent(document, 'keyup').pipe( | |
map((event: any) => event.target.value.trim() as string), | |
filter(text => text !== ''), | |
distinctUntilChanged(), | |
debounceTime(300), | |
switchMap(text => search(text)) | |
) | |
observable.subscribe({ | |
next(data) { | |
console.log(data) | |
setResults(data) | |
}, | |
}) | |
}, []) | |
return ( | |
<> | |
<input type="text" /> | |
{results.map(result => ( | |
<p key={result}>{result}</p> | |
))} | |
<button type="button" onClick={() => subject.next(new Date().toTimeString())}> | |
click | |
</button> | |
</> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment