Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import com.trello.rxlifecycle2.android.FragmentEvent
import io.reactivex.subjects.BehaviorSubject
/**
* Owner of a Fragment Lifecycle. Your Fragment should implement this interface.
*/
interface FragmentLifeCycleOwner {
val lifecycle: BehaviorSubject<FragmentEvent>
}
/**
* Base delegate that sets and disposes the fragment's listener when the parent is
* attached/detached.
*/
abstract class RxBaseParentDelegate<T>(private var fragment: Fragment?)
ReadOnlyProperty<Fragment, T> {
private var value: T? = null
init {
(fragment!! as FragmentLifeCycleOwner).lifecycle.subscribe { event ->
if (event === FragmentEvent.ATTACH) {
value = extractValue(fragment)
} else if (event === FragmentEvent.DETACH) {
value = null
fragment = null
}
}
}
/**
* Extract [T] from the fragment. This is called when the fragment is attached to the parent.
*/
abstract fun extractValue(fragment: Fragment): T?
operator fun setValue(thisRef: Fragment, property: KProperty<*>, value: T) {
throw IllegalStateException("Cannot set value on a ReadOnlyProperty")
}
override operator fun getValue(thisRef: Fragment, property: KProperty<*>): T {
return value!!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.