Created
December 5, 2020 08:03
-
-
Save serhii-pokrovskyi/f9908ed6cb167a4572eff1c1f08e461b to your computer and use it in GitHub Desktop.
Property that will be destroyed in onDestoy
This file contains hidden or 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
fun <T> LifecycleOwner.onDestroyNullable(): ReadWriteProperty<LifecycleOwner, T> = | |
object : ReadWriteProperty<LifecycleOwner, T>, DefaultLifecycleObserver { | |
private var value: T? = null | |
init { | |
this@onDestroyNullable | |
.lifecycle | |
.addObserver(this) | |
} | |
override fun onDestroy(owner: LifecycleOwner) { | |
value = null | |
this@onDestroyNullable | |
.lifecycle | |
.removeObserver(this) | |
super.onDestroy(owner) | |
} | |
override fun setValue(thisRef: LifecycleOwner, property: KProperty<*>, value: T) { | |
this.value = value | |
} | |
override fun getValue(thisRef: LifecycleOwner, property: KProperty<*>): T { | |
return value!! | |
} | |
} |
This file contains hidden or 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
private val someValue by onDestroyNullable<String>() |
is this can be used for Fragment view binding delegate? If so is there any example can you provide?
`private var binding by onDestroyNullable()
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
binding = FragmentAboutBinding.inflate(inflater, container, false)
return binding.root
}
`
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
is this can be used for Fragment view binding delegate? If so is there any example can you provide?