Last active
February 6, 2020 12:49
-
-
Save kibotu/5bc2abbb21e961b3df5df99e79e0302c to your computer and use it in GitHub Desktop.
Throttle KeyDown Events from MainActivity using Rx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyActivity : AppCompatActivity() { | |
private val emitter = KeyEventEmitter() | |
private var subscription by Delegates.notNull<CompositeDisposable>() | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
subscription = CompositeDisposable() | |
createKeyObservable(emitter) | |
.subscribe({ (keyCode, event) -> | |
// latest keyevent if there is one only every 100 ms | |
Log.v("keyevent", "$keyCode $event") | |
}, Throwable::printStackTrace) | |
.addTo(subscription) | |
} | |
override fun onDestroy() { | |
if (!subscription.isDisposed) | |
subscription.dispose() | |
super.onDestroy() | |
} | |
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { | |
emitter.onKeyDown(keyCode, event) | |
return super.onKeyDown(keyCode, event) | |
} | |
} | |
class KeyEventEmitter { | |
internal var keyDown: ((keyCode: Int, event: KeyEvent?) -> Unit)? = null | |
fun onKeyDown(keyCode: Int, event: KeyEvent?) { | |
keyDown?.invoke(keyCode, event) | |
} | |
} | |
fun createKeyObservable(keyEmitter: KeyEventEmitter) = BehaviorSubject.create<Pair<Int, KeyEvent?>> { emitter -> | |
if (emitter.isDisposed) | |
return@create | |
keyEmitter.keyDown = { keyCode, event -> | |
emitter.onNext(keyCode to event) | |
} | |
}.doOnDispose { keyEmitter.keyDown = null } | |
.throttleLatest(100, TimeUnit.MILLISECONDS) | |
.observeOn(AndroidSchedulers.mainThread()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment