Skip to content

Commit

Permalink
lifecycleProviderFromView
Browse files Browse the repository at this point in the history
  • Loading branch information
Pan committed Mar 10, 2021
1 parent 2c286a6 commit 9b6e9b4
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions rxlifecycle/src/main/java/com/ekoapp/rxlifecycle/RxView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,42 @@ package com.ekoapp.rxlifecycle

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import com.trello.rxlifecycle3.LifecycleProvider
import com.trello.rxlifecycle3.LifecycleTransformer
import com.trello.rxlifecycle3.RxLifecycle
import io.reactivex.Observable
import io.reactivex.subjects.BehaviorSubject

fun View.lifecycleProviderFromView(): LifecycleProvider<ViewEvent> {
val subject = BehaviorSubject.create<ViewEvent>()

addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(view: View?) {
subject.onNext(ViewEvent.ATTACH)
}

override fun onViewDetachedFromWindow(view: View) {
subject.onNext(ViewEvent.DETACH)
}
})

return object : LifecycleProvider<ViewEvent> {
override fun lifecycle(): Observable<ViewEvent> {
return subject.hide()
}

override fun <T : Any?> bindUntilEvent(event: ViewEvent): LifecycleTransformer<T> {
return RxLifecycle.bindUntilEvent<T, ViewEvent>(lifecycle(), event)
}

override fun <T : Any?> bindToLifecycle(): LifecycleTransformer<T> {
return bindUntilEvent(ViewEvent.DETACH)
}
}
}

abstract class RxView : LinearLayout, LifecycleProvider<ViewEvent> {

constructor(context: Context?) : super(context)
Expand Down

0 comments on commit 9b6e9b4

Please sign in to comment.