Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix leaking issue when add lifecycle observer #296

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions kotlin/src/main/java/app/rive/runtime/kotlin/RiveTextureView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,6 @@ abstract class RiveTextureView(context: Context, attrs: AttributeSet? = null) :
(sInNS / refreshRateHz).toLong()
}

init {
// Attach the observer to give us lifecycle hooks.
getContextAsType<LifecycleOwner>()?.lifecycle?.addObserver(lifecycleObserver)
}

private inline fun <reified T> getContextAsType(): T? {
var ctx = context
while (ctx is ContextWrapper) {
Expand All @@ -60,6 +55,15 @@ abstract class RiveTextureView(context: Context, attrs: AttributeSet? = null) :
return null
}

private fun addLifeCycleObserver() {
//`lifecycle` is already check and put if absent. So we just need to add `lifecycleObserver` without check is it already added or not.
getContextAsType<LifecycleOwner>()?.lifecycle?.addObserver(lifecycleObserver)
}

private fun removeLifeCycleObserver() {
getContextAsType<LifecycleOwner>()?.lifecycle?.removeObserver(lifecycleObserver)
}

override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {} // called every time when swapBuffers is called
override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {}

Expand All @@ -73,6 +77,7 @@ abstract class RiveTextureView(context: Context, attrs: AttributeSet? = null) :
// Only make the renderer once we are ready to display things.
renderer = createRenderer()
renderer!!.make()
addLifeCycleObserver()
}

@CallSuper
Expand All @@ -90,6 +95,7 @@ abstract class RiveTextureView(context: Context, attrs: AttributeSet? = null) :
// If we delete, we must have a Renderer.
renderer!!.delete()
renderer = null
removeLifeCycleObserver()
super.onDetachedFromWindow()
}

Expand Down