Last active
December 27, 2017 23:41
-
-
Save shikajiro/13d8104683e8db2f7a4c6178e8775e73 to your computer and use it in GitHub Desktop.
Implementation to make it easier to manage Composition of RxJava 2 using LifecycleObserver of Android Architecture Component and Delegate of Kotlin
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
/* Interface is necessary for Delegate */ | |
interface RxJava2LifecycleDelegate { | |
fun Disposable.autoDispose(): Disposable | |
fun Lifecycle.setupRxJava2Observer(func: () -> Unit) | |
} | |
/* Class for Delegate implementing LifecycleObserver */ | |
class RxJava2LifecycleDelegateImpl : RxJava2LifecycleDelegate { | |
private var composite = CompositeDisposable() | |
/** | |
* Extension function for registering LifecycleObserver and subscribe method | |
* @func: This lambda calls subscription processing | |
*/ | |
override fun Lifecycle.setupRxJava2Observer(func: () -> Unit) { | |
addObserver(RxJava2LifecycleObserver(composite, func)) | |
} | |
private fun check() { | |
if (composite.isDisposed) { | |
composite = CompositeDisposable() | |
} | |
} | |
/* Extension function for composite management of Disposable */ | |
override fun Disposable.autoDispose(): Disposable { | |
check() | |
composite.add(this) | |
return this | |
} | |
} | |
class RxJava2LifecycleObserver(private val composite: CompositeDisposable, | |
private val subscribeCallback: () -> Unit) | |
: LifecycleObserver { | |
/* It is automatically called at onResume timing and sets up subscription processing. */ | |
@OnLifecycleEvent(Lifecycle.Event.ON_START) | |
fun subscribe() { | |
subscribeCallback() | |
} | |
/* It is automatically called at the timing of onPause and releases subscription processing. */ | |
@OnLifecycleEvent(Lifecycle.Event.ON_STOP) | |
fun dispose() { | |
composite.dispose() | |
} | |
} |
Author
shikajiro
commented
Dec 27, 2017
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment