Skip to content

fix: keep native objects alive across Activity hide and reveal - #449

Merged
mfazekas merged 21 commits into
mainfrom
fix/activity-hide-disposal
Nov 17, 2026
Merged

mfazekas merged 21 commits into
mainfrom
fix/activity-hide-disposal

Conversation

@mfazekas

@mfazekas mfazekas commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #448

<Activity mode="hidden"> runs passive effect cleanups without unmounting, and useDisposableMemo, RiveView, useRiveFile and the async useViewModelInstance disposed native objects there, so the next call after a reveal hit a freed object: play was undefined, or release builds segfaulted.

useUnmountEffect frees only on a real unmount, and useRetainedEffect keeps async work (file loads, instances) across a hide instead of disposing and reloading. useDisposableMemo frees a replaced value only after the render that replaces it commits, and after the passive cleanups of that commit (#407). Both rely on hiding not running insertion-effect cleanups, which React tests but doesn't document; insertionEffectCanary.test.tsx checks it.

Root react moves to 19.2.3 so tests can use a real <Activity>; the reproducer runs in expo57-example. #466 adds the Android finalizers for the first gap below; the two PRs can merge in either order.

Known gaps:

  1. React Native's renderer before React 19.3 runs no cleanup when an already hidden <Activity> subtree unmounts, and no insertion cleanup when a Suspense-hidden subtree unmounts while suspended, so those objects are left to GC instead of being disposed. iOS frees them through deinit once Hermes collects their wrappers. On Android the native objects leak until fix(android): free native objects when their wrappers are garbage collected #466, and the legacy Android backend leaks them even with fix(android): free native objects when their wrappers are garbage collected #466.
  2. On iOS, Fabric recreates the native view on reveal, so riveViewRef changes (the replaced view is disposed).

<Activity mode="hidden"> runs passive cleanups without unmounting, so the
hooks disposed objects the component still held. The reveal then called
into them, which segfaults in release builds because Nitro skips its
null-NativeState check there. On Android the disposed view also stayed
blank with play/pause undefined, because the same native view survives
the hide.

Tell a real unmount from a hide with an insertion cleanup, which hide,
Strict Mode and Fast Refresh don't trigger on their own. Releasing still
happens in the passive phase, so a real unmount stays eager, and dev and
production now behave the same. useRiveFile and the async instance path
keep their run across a hide instead of disposing and reloading it.

React before 19.3 runs nothing when an already hidden subtree unmounts,
so native objects go with GC there. Android's file, instance and view
model had no finalizer and would leak for good on that path, so add one.
Properties and imperatively bound views now hold the instance wrapper,
so it can't be collected while they use the instance.

Root React moves to 19.2.3 so the tests can use a real <Activity>.

Fixes #448
useUnmountEffect now counts the insertion and passive effects that hold an
object and releases it in a microtask once neither does, so a child's passive
cleanup can still unsubscribe from an object its parent owns (#407).

useDisposableMemo keeps the render's candidate apart from the committed value
and frees a replaced value only after the replacing render commits, so a
transition that suspends no longer frees the value still on screen. Values from
renders that never commit are left to GC.

Adds a canary test for the insertion-effect semantics this relies on, and a
dev-only console.error when a component is retained again after its objects
were released.
11.16.3 delivers worker messages automatically and deprecates pollMessages,
so drop the per-frame polling loop. RiveSurface.resize is now public behind
@RiveImplementationApi, so call it directly instead of through reflection.
@mfazekas
mfazekas changed the base branch from main to chore/rive-android-11.16.3 November 11, 2026 08:36
…iew error

Both auto dataBind and defaultArtboardViewModel probe getDefaultViewModelInfo
and treat its failure as "no default ViewModel", but the command queue also
logs that failure at error level, which RiveErrorLogger forwarded to onError.
With 11.16.3 delivering worker messages immediately instead of on the next
polled frame, the error now reaches onError before the issue #189 harness
test asserts.
Base automatically changed from chore/rive-android-11.16.3 to main November 11, 2026 12:19
# Conflicts:
#	android/src/new/java/com/margelo/nitro/rive/HybridRiveFileFactory.kt
Key the async result to the deps of the run that produced it, so an
Activity reveal after A->B->A shows the retained instance instead of
loading forever, and a run settling while hidden is never paired with
newer inputs.
RiveView only disposed the last view it was handed, so every hide and
reveal on iOS left the previous view wrapper to GC.
The finalizer calls dispose() again after an explicit dispose, and the
second release unregistered assets a newer file had registered under the
same names. Also make the flags the finalizer reads volatile.
Comment thread src/hooks/useUnmountEffect.ts Resolved
The ref is replaced even if the teardown throws, so the new effect still
starts and the failed teardown is not called again on unmount.
useUnmountEffect and useDisposableMemo now use one useRetain hook. The
listener cleanups in useRiveProperty and useRiveTrigger drop their
try/catch: disposal waits for the passive cleanups, and the unsubscribe
closures don't touch the disposed object. The GC note now names the
Suspense case and React Native's renderer before React 19.3.

@ErikUggeldahl ErikUggeldahl left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for addressing the feedback. Looks good!

@mfazekas
mfazekas merged commit 3d4392c into main Nov 17, 2026
15 checks passed
@mfazekas
mfazekas deleted the fix/activity-hide-disposal branch November 17, 2026 19:21
mfazekas added a commit that referenced this pull request Nov 18, 2026
…lected (#466)

Pairs with #449 (#448). React before 19.3 (React Native 0.87 and older)
runs no cleanup when an already hidden `<Activity>` subtree unmounts, so
the wrappers of files, view models and instances in such a subtree are
left to GC, and on Android only `dispose()` freed their native memory.
This adds finalizers to `HybridRiveFile`, `HybridViewModel` and
`HybridViewModelInstance`. The two PRs can merge in either order.

Properties, active property listeners, bound views and pending async
queries hold the wrappers they depend on, so nothing is finalized while
in use. Async queries read the native object through the wrapper inside
the coroutine, which keeps the wrapper reachable until they complete. An
artboard set on a property needs no retention: the runtime's bindable
artboard holds a reference-counted pointer to its `File`, so finalizing
the source file's wrapper only drops its handle.

`HybridRiveFile` reports its size as `memorySize`, but that only informs
Hermes. ART can't see native memory, so a dropped file is freed only
when an unrelated Java heap collection runs its finalizer, not promptly.

`HybridRiveFile` keeps a `disposed` flag so a second `dispose()` from JS
doesn't unregister its assets again, and its finalizer skips a disposed
file and a view's empty placeholder file. View model instances and
artboards rely on rive-android's `close()`, which is idempotent. The
README notes under Known Issues that Android frees these objects through
finalizers and that the legacy backend has none.

`finalizer-ownership.harness.tsx` checks that a rebound view alias keeps
its instance open, that a listener on a nested or list-item instance
keeps firing after GC, and that artboards set on two nested instances
from two files keep advancing and remount after both files are finalized
(`artboard_slots.riv`, built from RML with `yarn build:artboard-slots`).
A control fails if nothing gets finalized.

Known gaps:
1. The legacy Android backend (`USE_RIVE_LEGACY`) has no finalizers, so
these objects still leak there.
2. Asset registration is global per name, so a late finalizer can
unregister assets that a newer file with the same name just registered
(#461).
3. The artboard created when a property is set is never closed, as on
`main`, so it and its source file stay in native memory until the Rive
worker shuts down, even after the property changes.
mfazekas pushed a commit that referenced this pull request Nov 19, 2026
🤖 I have created a release *beep* *boop*
---


##
[0.5.16](v0.5.15...v0.5.16)
(2026-11-18)


### Features

* add setValueAsync to ViewModelImageProperty
([#447](#447))
([f3bde90](f3bde90))


### Bug Fixes

* **android:** free native objects when their wrappers are garbage
collected
([#466](#466))
([2b47837](2b47837))
* keep native objects alive across Activity hide and reveal
([#449](#449))
([3d4392c](3d4392c))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

useDisposableMemo disposes native objects in effect cleanup, so a subtree hidden by React <Activity> crashes in release builds when shown again

2 participants