RxSwift - 去抖/节流“反向” [英] RxSwift - Debounce/Throttle "inverse"

查看:559
本文介绍了RxSwift - 去抖/节流“反向”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个即时消息应用程序,每次消息到达时都会发出哔声。我想 debounce 发出哔哔声,但是我想播放第一条消息的哔声而不是下面的消息(在2的时间段内,比方说,2)秒)。

Let's say I have an instant messaging app that plays a beep sound every time a message arrives. I want to debounce the beeps, but I'd like to play the beep sound for the first message arrived and not for the following ones (in a timespan of, say, 2 seconds).

另一个例子可能是:我的应用程序发送了输入通知(因此我正在聊天的用户可以看到我正在键入消息)。我想在开始输入时发送打字通知,但只在X秒间隔内发送新的通知,所以我不会为我输入的每个字符发送输入通知。

Another example might be: my app sends typing notifications (so the user I'm chatting with can see that I'm typing a message). I want to send a typing notification when I start typing, but only send new ones in X-seconds intervals, so I don't send a typing notification for every character I type.

这有意义吗?那有运营商吗?可以用现有的运算符实现吗?

Does this make sense? Is there an operator for that? Could it be achieved with the existing operators?

这是我的第一个例子的代码。我现在用 debounce 解决它,但它并不理想。如果我以1秒的间隔收到1000条消息,则在最后一条消息到达之前它不会播放声音(我想在第一条消息上播放声音)。

This is my code for the first example. I'm solving it now with debounce, but it's not ideal. If I receive 1000 messages in intervals of 1 second, it won't play the sound until the last message arrives (I'd like to play the sound on the first one).

self.messagesHandler.messages
            .asObservable()
            .skip(1)
            .debounce(2, scheduler: MainScheduler.instance)
            .subscribeNext { [weak self] message in
                    self?.playMessageArrivedSound()
            }.addDisposableTo(self.disposeBag)

谢谢!

推荐答案

更新了RxSwift 3并改进了 throttle operator

Updated for RxSwift 3 and improved throttle operator

新行为 throtlle 运算符,在RxSwift 3.0.0-beta.1中引入,您可以像这样使用它:

With new behavior of throtlle operator, introduced in RxSwift 3.0.0-beta.1, you can use it just like that:

    downloadButton.rx.tap
    .throttle(3, latest: false, scheduler: MainScheduler.instance)
    .subscribe(onNext: { _ in
        NSLog("tap")
    }).addDisposableTo(bag)






旧版本的答案

使用窗口运算符然后转换 Observable< Observable< Type>> to flat Observable 使用 flatMap

Use window operator and then transform Observable<Observable<Type>> to flat Observable using flatMap.

此示例代码仅在每3秒窗口中首次点击时打印点按(或点击计数超过10000)。

This sample code prints 'tap' only for first tap in every 3 seconds windows (or if tap count exceeds 10000).

    downloadButton.rx_tap
    .window(timeSpan: 3, count: 10000, scheduler: MainScheduler.instance)
    .flatMap({ observable -> Observable<Void> in
        return observable.take(1)
    })
    .subscribeNext { _ in
        NSLog("tap")
    }.addDisposableTo(bag)

这篇关于RxSwift - 去抖/节流“反向”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆