Skip to content

Instantly share code, notes, and snippets.

@brownsoo
Created October 1, 2018 01:23
Show Gist options
  • Save brownsoo/2271e8cdbb1b2d4aee90e194ce688ab1 to your computer and use it in GitHub Desktop.
Save brownsoo/2271e8cdbb1b2d4aee90e194ce688ab1 to your computer and use it in GitHub Desktop.
Implementation Double back key pressed to exit Using Rx
data class BackKeyPressedTimePair(val prev: Long, val curr: Long)
private var backSubject = PublishSubject.create<Boolean>()
// onBackPressed()
backSubject.throttleFirst(100, TimeUnit.MILLISECONDS)
.observeOn(uiScheduler)
.filter { isAvailable }
.map {
// if there is BottomSheet, hide that.
if (delayTimeSheetHolder?.isShowing == true) {
delayTimeSheetHolder?.hide()
true
} else if (bgmSheetHolder?.isShowing == true) {
bgmSheetHolder?.hide()
true
} else {
false
}
}
.filter { !it }
.map { BackKeyPressedTimePair(0, System.currentTimeMillis()) }
.scan { old, new -> BackKeyPressedTimePair(old.curr, new.curr) } // pairing old and new pressed time
.map { it.curr - it.prev }
.doOnNext {
// Toast message once
if (it > 1000L) {
showToast(R.string.double_tap_back_key_to_finish)
}
}
.filter { it < 1000L }
.take(1)
.compose { bindUntilViewDestroy(it) }
.subscribe {
// if there is ad to show when exit, shows that.
if (hasAd && !isInterstitialOpened) {
if (ggInterstitial?.isLoaded == true) {
ggInterstitial?.show()
} else if (fbInterstitial?.isAdLoaded == true) {
fbInterstitial?.show()
} else {
finish()
}
} else {
finish()
}
}
.addTo(disposableBag)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment