Last active
July 22, 2018 22:11
-
-
Save premnirmal/dd17cf04ebb6213cadd3f59540441147 to your computer and use it in GitHub Desktop.
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
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