Replies: 3 comments
-
To prevent memory leaks would be useful to add a delegate for an adapter clearing on view destroy. class AdapterDelegate<T : RecyclerView.Adapter<VH>, VH : RecyclerView.ViewHolder>(
private val fragment: Fragment,
private val adapterFactory: () -> T
) : ReadOnlyProperty<Any?, T>, LifecycleObserver {
private var adapter: T? = null
init {
fragment.viewLifecycleOwnerLiveData.observe(fragment) { lifecycleOwner ->
lifecycleOwner.lifecycle.addObserver(this)
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onViewDestroyed() {
adapter?.clear()
adapter = null
}
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return adapter ?: createNewAdapter()
}
private fun createNewAdapter(): T {
return adapterFactory.invoke().also { adapter = it }
}
}
fun <T : RecyclerView.Adapter<VH>, VH : RecyclerView.ViewHolder> Fragment.adapter(
adapterFactory: () -> T
): ReadOnlyProperty<Any?, T> {
return AdapterDelegate(this, adapterFactory)
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
Getters for non-nullable adapter and layout manager. inline fun RecyclerView.requireAdapter(): RecyclerView.Adapter<RecyclerView.ViewHolder> = checkNotNull(adapter)
inline fun <reified T : RecyclerView.LayoutManager> RecyclerView.requireLayoutManager(): T {
return checkNotNull(layoutManager) as T
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
inline fun RecyclerView.setupLinearLayoutManager(
@RecyclerView.Orientation orientation: Int = RecyclerView.VERTICAL,
reverseLayout: Boolean = false,
configure: LinearLayoutManager.() -> Unit = {},
) {
layoutManager = LinearLayoutManager(context, orientation, reverseLayout).apply(configure)
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Vote for the candidates that should be added to
recyclerview-ktx
in your opinionBeta Was this translation helpful? Give feedback.
All reactions