AutoDispose

 AutoDispose

Rx Ja Night #2
TwitterID変えました。@lvla0805 -> @MoyuruAizawa

5f533179da1c82722252cbcb93e7356f?s=128

Moyuru Aizawa

June 12, 2017
Tweet

Transcript

  1. AutoDispose @lvla0805

  2. lvla Ѫᖒ๖ (Moyuru Aizawa) - Kotlin engineer at CyberAgent, Inc.

    - FRESH! lvla0805
  3. override fun onCreate(…) { …
 Flowable.interval(1, TimeUnit.SECONDS)
 .subscribe { sec

    -> textView.text = "${sec}s" }
 } Disposable
  4. var disposable: Disposable? = null 
 override fun onCreate(…) {

    …
 disposable = Flowable.interval(1, TimeUnit.SECONDS)
 .subscribe { sec -> textView.text = "${sec}s" }
 } 
 override fun onDestroy() {
 disposable?.dispose()
 } Disposable
  5. val disposables = CompositeDisposable() 
 override fun onCreate(…) { …


    Flowable.interval(1, TimeUnit.SECONDS)
 .subscribe { sec -> textView.text = "${sec}s" }
 .addTo(disposables)
 } 
 override fun onDestroy() {
 disposables.dispose()
 super.onDestroy()
 } CompositeDisposable
  6. AutoDispose

  7. override fun onCreate(…) { …
 Flowable.interval(1, TimeUnit.SECONDS)
 .to(FlowableScoper<Long>(this))
 .subscribe {

    sec -> textView.text = "${sec}s" }
 } AutoDispose
  8. enum class ActivityLifeCycle {
 CREATE, …, DESTROY
 } AutoDispose

  9. public interface LifecycleScopeProvider<E> {
 Observable<E> lifecycle();
 Function<E, E> correspondingEvents();
 E

    peekLifecycle();
 } AutoDispose
  10. abstract class RxActivity : AppCompatActivity(), LifecycleScopeProvider<ActivityLifeCycle> { … } AutoDispose

  11. ‣ lifecycle() ‣ returns an Observable of lifecycle events. ‣

    This should be backed by a BehaviorSubject or something similar ‣ correspondingEvents() ‣ a mapping of events to corresponding ones. ‣ i.e. CREATE -> DESTROY ‣ peekLifecycle() ‣ returns the current lifecycle state of the object. AutoDispose
  12. abstract class RxActivity : AppCompatActivity(),
 LifecycleScopeProvider<ActivityLifeCycle> {
 
 private val

    lifecycle = BehaviorSubject.create<ActivityLifeCycle>()
 private lateinit var currentEvent: ActivityLifeCycle
 
 override fun lifecycle(): Observable<ActivityLifeCycle> = lifecycle
 
 override fun correspondingEvents(): Function<ActivityLifeCycle, ActivityLifeCycle> {
 return Function { lastEvent: ActivityLifeCycle ->
 when (lastEvent) {
 CREATE -> DESTROY
 else -> throw OutsideLifecycleException("Activity was destroyed")
 }
 }
 }
 
 override fun peekLifecycle() = currentEvent
 } AutoDispose
  13. class MainActivity : RxActivity() {
 …
 override fun onCreate(…) {


    Flowable.interval(1, TimeUnit.SECONDS)
 .to(FlowableScoper<Long>(this))
 .subscribe { sec -> textView.text = "${sec}s" }
 }
 } AutoDispose
  14. Thank you