Hello i am writing a app which uses many customView(parent as FrameLayout holding activity's context).
In the app there is a recyclerView it's holder is having N
(significantly large number) of view's(Custom).
As the number of View's are dynamically added (i am testing for 10k+ view's).
in recycler View i am not doing anything special but using coroutine's so that rendering of 10k view will not block the Main Thread
But due to large number's of View's in each RecyclerView Holder it's Filling up the heap memory of the app very fast as i scroll and give's OOM(Out of Memory) Crash.
To solve this issue i read and found I can use weak reference's to the View.But i have not found any example or reference to this approach.So i am not sure if using WeakReference on the Android View is a good solution or not.
Code and Demo Project Reference Below.
RecyclerView Adapter :
override fun onBindViewHolder(holder: ViewPageHolder, position: Int) {
val slideViewMultipleCanvas = SlideViewMultipleCanvas(context)
holder.slideViewItemHolder.addView(slideViewMultipleCanvas)
holder.positionHolder = position
val childJob = launch {
//this is where 10k+ view's are created
slideViewMultipleCanvas.setNumOfObjects(numOfItemsInViewPage)
slideViewMultipleCanvas.startJob()
}
map[position] = childJob
}
CustomView :
...
...
suspend fun setNumOfObjects(numberOfObjects: Int) {
withContext(Dispatchers.Default) {
for (i in 0 until numberOfObjects) {
// To solve OOM as number of view here in heap are >10k
listOfObject.add(WeakReference(ShapeView(context)))
}
}
}
...
...
private fun addViewInScope(): Boolean {
for (shapeView in listOfObject) {
shapeView.get()?.let {
addView(it)
}
}
return true
}
....
....
After Using WeakReference from my testing i have not faced any issue(NO OOM's
) till now but still i get Lag's whenever GC(Garbage Collector)
kick's in and collect all the weak reference.
My Main concerns are
- Is There any other way to handle creation of huge number of View without using WeakReference?
- Is there any issue's if i use weak reference for Views?
- how to decrease GC lag?(even using WeakReference i am not getting smooth scroll)
P.S. : I am already handling:
- null cases if GC collect's the weak referenced View's
- cancelling coroutine job's when view is recycled in RecyclerView.(can i release the weak Referred view also of this ViewHolder also???)