4 ms·
it's much more scalable to write time-dependent code like this in a reactive stream library like RxJS or Bacon. Rx example: Rx.fromEvent(input, 'keyup') /
by beaconstudios 7y ago
it's much more scalable to write time-dependent code like this in a reactive stream library like RxJS or Bacon.
Rx example:
Rx.fromEvent(input, 'keyup') // stream of keyup events
.pipe(map(e => e.target.value)) // map to stream of values
.pipe(debounceTime(1000)) // debounce the stream
.subscribe(value => console.log('text', value));
this scales linearly with the addition of time-dependent features - say you want to map that value stream into an API request ie a Promise, but you want to only have the latest Promise actually write to your output in case an earlier request took longer to complete and finished after the latest one. That goes like this:
Rx.fromEvent(input, 'keyup') // stream of keyup events
.pipe(map(e => e.target.value)) // map to stream of values
.pipe(debounceTime(1000)) // debounce the stream
.pipe(switchMap(value => axios.get(`${API}/endpoint`))) // switchMap is like a stream version of flatMap, but only uses the latest result
.subscribe(response => setState({ results: response.data }));
you can do things like that with plain JS, but it gets convoluted very quickly.
you can do a lot of clever stuff with this stream manipulation. I've managed to build some complex pieces of drag and drop UI in a few lines of code using Rx and React.
- barnaclejive 7y agoWait for User to Stop Typing, in Rx.