Skip to content

Instantly share code, notes, and snippets.

@serhii-pokrovskyi
Created December 5, 2020 08:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serhii-pokrovskyi/f9908ed6cb167a4572eff1c1f08e461b to your computer and use it in GitHub Desktop.
Save serhii-pokrovskyi/f9908ed6cb167a4572eff1c1f08e461b to your computer and use it in GitHub Desktop.
Property that will be destroyed in onDestoy
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!!
}
}
private val someValue by onDestroyNullable<String>()
@suryagopal
Copy link

is this can be used for Fragment view binding delegate? If so is there any example can you provide?

@serhii-pokrovskyi
Copy link
Author

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