例如,我在我的应用程序中有一个简单的管理器,其中我试图保持一切“响应式”:
class AppLockManager {
private val logger = LoggerFactory.getLogger(javaClass)
private val rxHelper: RxHelper
private val securityManager: DiarySecurityManager
private var locked = false
private var lastUnlockTime: LocalDateTime? = null
constructor(rxHelper: RxHelper, securityManager: DiarySecurityManager) {
this.rxHelper = rxHelper
this.securityManager = securityManager
}
fun shouldLock(): Observable<Boolean> {
return securityManager.isSecutiryEnabled()
.doOnNext { logger.debug("isSecurityEnabled: $it") }
.map { it && !locked && isLockTimerExpired() }
.doOnNext { logger.debug("shouldLock: $it") }
.compose(rxHelper.applySchedulers())
}
private fun isLockTimerExpired(): Boolean {
if(lastUnlockTime == null) return true
val timerExpiredMoment = lastUnlockTime!!.plusSeconds(30)
val now = LocalDateTime.now().isAfter(timerExpiredMoment)
val isExpired = LocalDateTime.now().isAfter(timerExpiredMoment)
logger.debug("timerExpiredMoment: $timerExpiredMoment / now: $now; isExpired: $isExpired")
return isExpired
}
fun setLocked(): Observable<Void> {
return Observable.create<Void> {
this.locked = true
it.onCompleted()
}.compose(rxHelper.applySchedulers())
}
fun setUnlocked(): Observable<Void> {
return Observable.create<Void> {
this.locked = false
lastUnlockTime = LocalDateTime.now()
}.compose(rxHelper.applySchedulers())
}
fun resetLockTimer(): Observable<Void> {
return Observable.create<Void> {
lastUnlockTime = LocalDateTime.now()
}.compose(rxHelper.applySchedulers())
}
}
这是一个简单的类,用于计时并在我的应用程序需要锁定时从shouldLock()
中发出true
。
以下是我如何使用它:
fun lockAppIfNeeded() {
appLockManager.shouldLock()
.doOnNext { logger.debug("shouldLock: $it") }
.flatMap { if(it == true) Observable.just(it) else Observable.never() } // flow down only if it == true
.flatMap { appLockManager.setLocked() } // then lock
.subscribe(sub({}, Throwable::printStackTrace, { // use onComplete as source Observable is empty
securityManager.anyPassword().subscribe {
if (it) {
view.navigateToAskPassword() // anyPassword is true
} else {
view.navigateToFirstPasswordSetup() // anyPassword is false
}
}
}))
}
看起来很丑,是吗?:)
我就是找不到正确的操作符来结合空Observable(appLockManager.setLocked()
)和返回发出一个项目的Observable(securityManager.anyPassword()
)。
这使我认为我不应该在appLockManager.setLocked()
等方法中使用RxJava。
我应该在这里使用Observables吗? 特别是对于仅更新AppLockManager
并根本不返回数据的setLocked()
/setUnlocked()
/resetLockTimer()
方法。
Completable
的信息。它在最新的RxJava
更新中成为了@Beta
版本,而且正好符合我的需求。 - Alexandr