Skip to content

Instantly share code, notes, and snippets.

@k-kagurazaka
Last active December 20, 2017 01:35
Show Gist options
  • Save k-kagurazaka/8f1306ffc53389e69c903ffe24bf6827 to your computer and use it in GitHub Desktop.
Save k-kagurazaka/8f1306ffc53389e69c903ffe24bf6827 to your computer and use it in GitHub Desktop.
RxCommand with double context extension pattern
interface HasDisposables {
fun Disposable.autoDispose()
fun dispose()
companion object {
operator fun invoke(): HasDisposables = object : HasDisposables {
private val disposables = CompositeDisposable()
override fun Disposable.autoDispose() {
disposables.add(this)
}
override fun dispose() {
disposables.clear()
}
}
}
}
val HasDisposables.subscribeWithAutoDispose: RxCommand<NoParameter>.(() -> Unit) -> RxCommand<NoParameter>
get() = { onNext ->
apply { subscribe { onNext() }.autoDispose() }
}
class SomeViewModel : HasDisposables by HasDisposables() {
val command: RxCommand<NoParameter> = RxCommand<NoParameter>().subscribeWithAutoDispose {
// command action
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment