如何使用 RxJS 显示“用户正在输入"指标? [英] How to use RxJS to display a "user is typing" indicator?
问题描述
我对 BaconJS 略知一二,但现在我正在尝试通过创建用户正在输入..."指示器来学习 RxJS.很简单,可以用两个简单的规则来解释:
I know a little bit of BaconJS, but now I'm trying to learn RxJS by creating a "User is typing..." indicator. It's pretty simple, it can be explained in two simple rules:
- 当用户输入时,指示器应该立即可见.
- 当用户停止输入时,指示器应该仍然可见,直到用户最后一次输入操作后 1 秒.
我不确定这是否正确,但到目前为止我已经创建了两个流:
I'm not sure if this is correct, but I have so far created two streams:
- 每秒发出一个
0
的心跳流. - 一个流来捕获用户输入事件并为每个事件发出一个
1
.
- One heartbeat stream that emits a
0
every second. - One stream to capture the user typing events and emit a
1
for every event.
然后我将它们合并在一起,然后简单地点击结果.如果它是 1
,那么我会显示指示器.如果它是 0
,那么我隐藏指示器.
Then I merge them together, and simply tap into the result. If it's a 1
, then I show the indicator. If it's a 0
, then I hide the indicator.
看起来是这样的:
const showTyping = () =>
$('.typing').text('User is typing...');
const showIdle = () =>
$('.typing').text('');
// 1 second heartbeats are mapped to 0
const heartbeat$ = Rx.Observable
.interval(1000)
.mapTo(0);
// user typing events are mapped to 1
const input$ = Rx.Observable
.fromEvent($('#input'), 'input')
.mapTo(1);
// we merge the streams together
const state$ = heartbeat$
.merge(input$)
.do(val => val === 0 ? showIdle() : showTyping())
.subscribe(console.log);
这是JSBin的链接:
Here is a link to the JSBin:
http://jsbin.com/vekixuv/edit?js,console,output
我对这个实现有几个问题和疑问:
There are several problems and questions I have with this implementation:
- 有时,当用户正在输入时,
0
会偷偷通过,因此指示灯会闪烁一秒钟,然后在下一次用户击键时返回. - 不保证指示器会在用户停止输入 1 秒后消失.只能保证指示器会在 1 秒内消失(这与我们想要的正好相反).
- 使用心跳流是正确的 RxJS 方法吗?我有一种感觉可能不是.
- Sometimes when the user is typing, a
0
sneaks through, so the indicator flashes away for a split second before coming back on the next user keystroke. - It's not guaranteed that the indicator will disappear 1 second after the user stops typing. It's only guaranteed that the indicator will disappear within 1 second (which is kind of the opposite of what we want).
- Is using a heartbeat stream the correct RxJS way to do this? I have a feeling it might not be.
我觉得我的实现完全偏离了基础,感谢您提供的任何帮助.谢谢.
I have a feeling that I am completely off-base with my implementation, I appreciate any help that you may be able to provide. Thanks.
推荐答案
你甚至不需要使用两个 Observable 并且只使用一个带有 debounceTime()
.您尝试创建的所有逻辑都已存在于 debounceTime()
运算符中:
You don't even need to use two Observables and use just one with debounceTime()
. All the logic you tried to make is already present in debounceTime()
operator:
const showTyping = () =>
$('.typing').text('User is typing...');
const showIdle = () =>
$('.typing').text('');
const input$ = Rx.Observable
.fromEvent($('#input'), 'input')
.do(() => showTyping())
.debounceTime(1000)
.subscribe(() => showIdle());
查看现场演示:http://jsbin.com/cixipa/6/编辑?js,控制台,输出
这篇关于如何使用 RxJS 显示“用户正在输入"指标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!