Skip to content

Instantly share code, notes, and snippets.

@ChristopherME
Last active March 25, 2023 14:05
Show Gist options
  • Save ChristopherME/82d34b68b8b4d0968ff4ebb6b379afec to your computer and use it in GitHub Desktop.
Save ChristopherME/82d34b68b8b4d0968ff4ebb6b379afec to your computer and use it in GitHub Desktop.
This extension method is a solution for a memory leak problem with recyclerviews.
/**
* Set the adapter and call [clearReference] extension function in one call.
* Use this extension if the current Fragment is going to be REPLACED. (When using fragmentTransaction.add is not necessary) the back stack.
*/
fun <VH : RecyclerView.ViewHolder> RecyclerView.setNullableAdapter(
adapter: RecyclerView.Adapter<VH>
) {
this.adapter = adapter
this.clearReference()
}
/**
* Remove the adapter after the view has been detached from window in order to prevent memory leaks.
*/
internal fun RecyclerView.clearReference() {
addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(v: View?) {
}
override fun onViewDetachedFromWindow(v: View?) {
this@clearReference.adapter = null
}
})
}
// Usage in your fragment or activity ->
viewDataBinding.myRv.setNullableAdapter(adapter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment