首页 > 解决方案 > Observable.interval 不在后台状态下工作

问题描述

我正在尝试使用 RxSwift 创建一个简单的计时器,我的灵感来自这个答案 ()。当应用程序在前台时它工作正常。问题是,如果应用程序状态进入后台,它会停止,然后如果应用程序状态再次进入前台,则从它停留的位置开始计数。

https://stackoverflow.com/a/41198811/3950721

快速浏览; 带有 RxSwift 的简单计时器

标签: iosswiftbackgroundrx-swift

解决方案


您正在经历的是标准和预期的行为。当应用程序进入后台时,所有计时器和其他后台任务(无论是否在 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)

推荐阅读