Last active
March 25, 2023 14:05
-
-
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.
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
/** | |
* 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?) { | |
[email protected] = 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