Skip to content

fix(android): free native objects when their wrappers are garbage collected - #466

Merged
mfazekas merged 19 commits into
mainfrom
fix/android-finalize-native-objects
Nov 18, 2026
Merged

mfazekas merged 19 commits into
mainfrom
fix/android-finalize-native-objects

Conversation

@mfazekas

@mfazekas mfazekas commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

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 ([iOS][Android] New backend: disposing one RiveFile removes a referenced font from every other live file with the same asset name #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.

…lected

React before 19.3 runs no cleanup when an already hidden subtree unmounts,
so the JS wrappers of files, view models and instances are left to GC, and
on Android only dispose() freed their native memory. Add finalizers, keep
the instance wrapper reachable from its properties and bound views so it
can't be closed while in use, and make dispose() idempotent so a finalizer
running after an explicit dispose doesn't release a file's assets twice.

Refs #448

@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.

LLM finding: Source review identified two potential lifetime gaps introduced by finalizing the wrappers. The inline comments explain the ownership paths and suggested regression coverage. These have not been reproduced on an emulator.

getViewModelNamesAsync, getArtboardCountAsync, getArtboardNamesAsync,
getEnums and ViewModelInstance.getPropertiesAsync captured only the raw
RiveFile, so the wrapper could be finalized and close the file before the
query ran. Hold the owning file wrapper until the coroutine completes.
RiveView.getViewModelInstance() returns a non-owning alias. Rebinding that
alias replaced the view's reference to the owning wrapper, whose finalizer
then closed the instance the view and alias still used. Aliases now hold
the owning wrapper.
…uses it

An artboard set on a property is created from another file's native handle,
so the instance now holds that file's wrapper and its finalizer can't close
the file while the artboard is bound.
Without a memorySize hint Hermes treats the file wrapper as tiny and collects
dropped files too rarely for their finalizers to free the native file.
boundViewModelInstance was never cleared, so a view kept an imperatively bound
instance alive after dataBind replaced it. Drop it once the view holds another
instance, and mark it volatile since getViewModelInstance() reads it on the JS
thread.
The ownership test also passed when gc was missing or no finalizer ran. Log at
debug level when a file is finalized without dispose(), and add a control that
expects that log for an unreferenced file.
A listener's collecting coroutine held only the property delegate, so a nested or list-item instance that JS no longer referenced could be finalized, closing its handle and silently ending the listener.
Each query coroutine now reads the native object through the wrapper, so it
holds the wrapper until it completes and AsyncRetaining is no longer needed.
ViewModelInstance and Artboard close through CloseOnce, so their own closed
state replaces the wrapper flags. HybridRiveFile keeps its flag, which stops a
second dispose() from unregistering assets again.
A nested or list-item wrapper can be dropped while its artboard stays bound,
so these wrappers now hold their parent and the source file is stored on the
root of that chain.
mfazekas added a commit that referenced this pull request Nov 17, 2026
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 #466, and the legacy Android backend leaks them even
with #466.
2. On iOS, Fabric recreates the native view on reveal, so `riveViewRef`
changes (the replaced view is disposed).
A view holds an empty HybridRiveFile until its file prop arrives. When it
was collected, its finalizer logged a file "garbage collected without
dispose" that never had a native file, which the harness counts as a
freed file.
A bound artboard holds a reference-counted pointer to its File, and
deleting the file handle only drops that handle, so closing the source
file's wrapper is safe while its artboard stays bound. The wrapper
retention keyed by relative path also let two instances overwrite each
other's entry. Nested and list-item wrappers no longer hold their parent,
which only served that retention; their native handles are independent.
Two nested instances with an `icon` artboard property at the same path
are set from two files; after both files are finalized, both artboards
keep advancing and mount again in a new view.

@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 going through the rounds of feedback. Looks good to merge!

@mfazekas
mfazekas enabled auto-merge (squash) November 18, 2026 19:52
@mfazekas
mfazekas merged commit 2b47837 into main Nov 18, 2026
15 checks passed
@mfazekas
mfazekas deleted the fix/android-finalize-native-objects branch November 18, 2026 20:14
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.

2 participants