ios - Observable.interval 不在后台状态下工作
问题描述
我正在尝试使用 RxSwift 创建一个简单的计时器,我的灵感来自这个答案 ()。当应用程序在前台时它工作正常。问题是,如果应用程序状态进入后台,它会停止,然后如果应用程序状态再次进入前台,则从它停留的位置开始计数。
https://stackoverflow.com/a/41198811/3950721
快速浏览; 带有 RxSwift 的简单计时器
解决方案
您正在经历的是标准和预期的行为。当应用程序进入后台时,所有计时器和其他后台任务(无论是否在 Rx 中)都会停止。
为了让任何人帮助您,您需要解释您正在尝试做什么,以便我们可以想出另一种方法来做到这一点。
例如,在我的一个应用程序中,用户应该在 5 分钟不活动后退出,所以我有这个来确保它发生:
let idleTime = 5 * 60
let foregroundTimerTripped = Observable.merge(
application.rx.methodInvoked(#selector(UIApplication.sendEvent(_:))).map(to: ()),
rx.methodInvoked(#selector(UIApplicationDelegate.applicationWillEnterForeground(_:))).map(to: ())
)
.debounce(.seconds(idleTime), scheduler: MainScheduler.instance)
let backgroundTime = rx.methodInvoked(#selector(UIApplicationDelegate.applicationDidEnterBackground(_:)))
.map(to: ())
.flatMap { Observable.just(Date()) }
let foregroundTime = rx.methodInvoked(#selector(UIApplicationDelegate.applicationWillEnterForeground(_:)))
.map(to: ())
.flatMap { Observable.just(Date()) }
let backgroundTimerTripped = foregroundTime
.withLatestFrom(backgroundTime) { $0.timeIntervalSince($1) }
.filter { $0 > TimeInterval(idleTime) }
.withLatestFrom(bearer)
let timeToLogout = Observable.merge(foregroundTimerTripped, backgroundTimerTripped)
推荐阅读
- r - 反应图是映射变量名吗?
- alexa - “Alexa,打开 Mighty Righty” - 有效 /// “Alexa,问 Mighty Righty 谁是对的,我还是我丈夫”不起作用(嗯,我不知道那个)
- sql-server - Spring Batch for DB2 to SQL 批量键迁移
- unit-testing - 在结构内部的方法中测试错误响应
- python - 让我的机器人离开特定公会的命令:discord.py rewrite
- wpf - ScrollViewer 宽度变窄
- javascript - 在仪表板页面上显示实时计数器
- html - 移动浏览器的负定位绝对div问题
- javascript - 为什么 snap.data().id 没有定义?
- javascript - react-native-image-slider (不能显示本地图片)