使用iOS中的Combine Framework根据价值向发布服务器添加延迟
我有一个出版商使用iOS中的Combine Framework根据价值向发布服务器添加延迟,ios,swift,combine,Ios,Swift,Combine,我有一个出版商 public let motionSubject=PassthroughSubject() 我在用价值观倾听 motionManager.motionSubject.sink(receiveValue: { [weak self] isMoving in self?.isMoving = isMoving }).store(in: &subscription) 如果发布的值为“true”,我想添加2秒延迟,因为我想提供2秒的声音反馈 我试图在motionSubj
public let motionSubject=PassthroughSubject()
我在用价值观倾听
motionManager.motionSubject.sink(receiveValue: { [weak self] isMoving in
self?.isMoving = isMoving
}).store(in: &subscription)
如果发布的值为“true”,我想添加2秒延迟,因为我想提供2秒的声音反馈
我试图在motionSubject.send之前添加DispatchQueue.asynafter(true),但没有成功
有人知道我怎样才能做到这一点吗
谢谢。您可以使用.throttle或.debounce,我认为在您的情况下,throttle会更有用,因为它在收到值后不会暂停。 因此,如果要专门针对真实值执行此操作,则需要执行以下操作:
motionManager.motionSubject
.filter { $0 == true } // will only emit through values which answer this query
.throttle(for: .milliseconds(2000), scheduler: DispatchQueue.main, latest: true) // will publish the latest value after 2 seconds delay since the first pulishment
.sink(receiveValue: { [weak self] isMoving in
self?.isMoving = isMoving
}).store(in: &subscription)
是否要将延迟添加到更改
isMoving
中,或同时延迟motionSubject
中的后续值?那么,如果motionSubject
发出true
,然后1s后它会发出另一个值(无论是true
还是false
),该怎么办呢?实际上,对于我的场景,我可以在2秒钟内忽略这些值。2秒后,它应该重新计算当前位置的移动逻辑。实际上drop
会丢弃这些值。您要查找的是过滤器
,它是发出符合指定条件的值的运算符<代码>删除的作用正好相反,它会丢弃符合条件的值。你完全正确,我更新了答案