refactor(android): keep state for plain native objects in JS by edusperoni · Pull Request #11664 · NativeScript/NativeScript
Repository navigation
refactor(android): keep state for plain native objects in JS - #11664
Draft
edusperoni wants to merge 3 commits into main from refactor/android-native-object-state
Draft
refactor(android): keep state for plain native objects in JS #11664 edusperoni wants to merge 3 commits into main from refactor/android-native-object-state
Conversation
edusperoni commented Nov 22, 2026 · edited Loading
Copy link Copy Markdown
Contributor
PR Checklist
- The PR title follows our guidelines: https://github.com/NativeScript/NativeScript/blob/master/tools/notes/CONTRIBUTING.md#commit-messages .
- There is an issue for the bug/feature this PR is for. To avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it.
- You have signed the CLA .
- All existing tests are passing (unit tests yes;
apps/automatedon device not yet run): https://github.com/NativeScript/NativeScript/blob/master/tools/notes/DevelopmentWorkflow.md#unit-testing . - Tests for the changes are included - https://github.com/NativeScript/NativeScript/blob/master/tools/notes/WritingUnitTests.md .
What is the current behavior?
On Android, core stores JS properties ("expandos") on plain Java objects, meaning objects that are not instances of a JS-extended class: listener back-references on native views, the default background drawable, default paddings, the SeekBar owner, the Frame attach-listener owner, animator transition data, and activity callbacks/flags on embedded host activities.
The Android runtime is adding a wrapper-lifetime ("canary") mode in which the JS wrapper of a Java object can be collected and rebuilt later. Expandos on plain objects then have to be mirrored into side state, and reading them costs roughly 10× more under the design the runtime will default to. The Node-API/JSI runtimes go further and drop that state when the wrapper dies. Expandos on JS-extended instances (@NativeClass / .extend()) are unaffected, because the JS object is the implementation.
What is the new behavior?
Core keeps that state in JS, next to where the native object is already held:
- View fields for listener back-references (the View already owns
nativeViewProtected), the cached default background, and the ListView search wrapper. - Per-owner listener instances where a shared listener recovered its owner from an expando on the native object it was handed: Slider (
seekBar.owner), the Frame attach listener (view[ownerSymbol]) and fragment animators (animator.entry/animator.transitionType). Each listener holds aWeakRefto its owner or entry, so no JS→Java→JS cycle keeps a view alive. - WeakMap/WeakSet only where there is no JS owner (see below).
Teardown is unchanged: listeners still get owner = null in disposeNativeView, and their View fields are released. No changes to the public barrel API. ui/utils.d.ts drops the exported NativeScriptAndroidView type, which only declared the _cachedDrawable expando (see Open questions).
Inventory
Line numbers are on main at this PR's original base (b1fdbd5 ) and have shifted slightly since; paths are relative to packages/core/.
Already done on main (dropped from this PR when it was rebased):
- fix(android): keep TabView and ListPicker child views off their native views #11661 moved ListPicker's
editTextand TabView'sviewPager/tabLayout/viewPager.adapteroff the native views onto View fields. - fix(android): hold Button and ActionBar from their native listeners weakly #11658 made the Button and ActionBar listeners hold their owner through a
WeakRef. TheclickListener/menuItemClickListenerexpandos on the native views are still onmain, so this PR still moves them to View fields, typed for the weak owner. - fix(android): stop fragment transition listeners from holding their transition #11656 removed the transition back-reference from the fragment
TransitionListener. This PR's fragment change covers theAnimatorlisteners only.
Plain objects (changed)
| Site | Object | Fix |
|---|---|---|
ui/core/view-base/index.ts:1233,1237-1238 defaultPaddings writes |
every View's native view | Writes dropped; the per-class DEFAULT_VIEW_PADDINGS cache already holds the value. The read fallback at :1230 stays (see Open questions). |
ui/core/view/index.android.ts:1666,1693,1755-1762 _cachedDrawable |
every View's native view | View._cachedDrawable, paired with the native view it was captured from, so a swapped native view (setNativeView) recaptures its default. Reset in disposeNativeView. |
ui/core/view/view-helper/index.android.ts:24,38,50 _backgroundColor |
Drawable (from getBackground() etc.) |
Module WeakMap<Drawable, number> (no JS owner) |
ui/button/index.android.ts:81,86 clickListener |
android.widget.Button |
Button._clickListener (the listener's owner is already weak since #11658 ) |
ui/switch/index.android.ts:51,57 listener |
android.widget.Switch |
Switch._checkedChangeListener |
ui/image/index.android.ts:79,84 listener |
org.nativescript.widgets.ImageView |
Image._imageLoadedListener |
ui/date-picker/index.android.ts:78,95 listener |
android.widget.DatePicker |
DatePicker._dateChangedListener |
ui/time-picker/index.android.ts:54-55 listener, calendar |
android.widget.TimePicker |
Both were never read back: listener expando dropped, calendar is a local |
ui/editable-text-base/index.android.ts:115,122-126 listener |
android.widget.EditText |
EditableTextBase._editTextListeners |
ui/search-bar/index.android.ts:154,158,164,167 queryTextListener / closeListener |
androidx.appcompat.widget.SearchView |
SearchBar._queryTextListener / _closeListener |
ui/action-bar/index.android.ts:176,181 menuItemClickListener |
androidx.appcompat.widget.Toolbar |
ActionBar._menuItemClickListener (the listener's owner is already weak since #11658 ) |
ui/web-view/index.android.ts:119,126-127 client |
android.webkit.WebView |
WebView._webViewClient |
ui/list-view/index.android.ts:166,170,184,187 adapter / itemClickListener |
android.widget.ListView |
ListView._listViewAdapter / _itemClickListener |
ui/list-view/index.android.ts:767 and 10 reads, _searchView._wrapper |
android.widget.SearchView |
ListView._searchViewWrapper (not in the earlier sweep) |
ui/list-picker/index.android.ts:113-121,133-137,146-148 formatter / valueChangedListener |
android.widget.NumberPicker |
ListPicker._formatter / _valueChangedListener. editText → _editText is already on main (#11661 ). |
ui/tab-view/index.android.ts:544,548,551,573-578 viewPager / tabLayout / viewPager.adapter |
GridLayout, TabViewPager |
Already on main (#11661 ); no longer in this PR |
ui/slider/index.android.ts:29,68,75 seekBar.owner read by a shared listener |
android.widget.SeekBar |
One listener per Slider, holding WeakRef<Slider> |
ui/frame/index.android.ts:48,54,502,516 view[ownerSymbol] read by a shared attach listener |
Frame's ContentLayout |
One attach listener per Frame, holding WeakRef<Frame>. Removed in disposeNativeView. |
ui/frame/fragment.transitions.android.ts:259-286,303-336,357-362 animator.entry / transitionType |
Animator from createAndroidAnimator |
One AnimatorListener per animator, holding the entry WeakRef and type. Exit/popEnter listeners are kept on the entry so they can be removed. animator.backEntry was read but never written, so it is now undefined explicitly. |
ui/frame/activity.android.ts:80-86 and the embedded callbacks, isNativeScriptActivity / _callbacks |
embedded host activity (plain) | Activity registry (ui/frame/activity-callbacks-store.ts, WeakMap) |
ui/frame/index.android.ts:1186-1192 _callbacks / _onBackPressed in setActivityCallbacks |
any activity | Registry for both modes. activity._callbacks is still written outside embedded mode (see below). |
ui/frame/index.android.ts:87,758,965, application/application.android.ts:97,209,799,838,853, native-window/native-window.android.ts:107, reads and in probes |
any activity, including third-party ones | getActivityCallbacks() / isNativeScriptActivity() from the registry |
Extended or JS objects (unchanged)
| Site | Why it stays |
|---|---|
ui/frame/activity.android.ts:23-66 this.isNativeScriptActivity / this._callbacks |
com.tns.NativeScriptActivity is .extend()-ed |
activity._callbacks written by setActivityCallbacks outside embedded mode |
Activities are NativeScriptActivity or user @NativeClass activities, and the documented custom-activity pattern reads this._callbacks |
ui/frame/fragment.android.ts this._callbacks, frame-helper-for-android.ts:49,358, ui/frame/index.android.ts:279 fragment[CALLBACKS] |
com.tns.FragmentClass is extended |
ui/segmented-bar/index.android.ts:232,240 nativeView.listener |
native view is TabHostImpl (@NativeClass) |
callback['_activity'] (frame), callback['_dialog'] (view), .owner on listener instances, _pagerAdapter.items |
all @NativeClass / .extend() instances |
http/http-request-internal/index.android.ts:128 Object.assign(content, ...) |
content is a JS object literal |
javaOptions.* (http), lp.gravity / lp.weight / lp.row / flexbox and dock lp.*, Utils.ignoreEdgeToEdgeOnOlderDevices |
Java public (or static) fields. lp.weight is only written when the read returned a number, i.e. a real LinearLayout.LayoutParams.weight |
'setOverflowEdge' in nativeView (view) |
method-existence probe on the prototype, not an expando |
args.view._listViewItemIndex, view['_lastText'] (a11y helpers), nativeWindow._surfaceGone, itemSpec.owner |
JS objects |
WeakMap / WeakSet fallbacks
AndroidHelperdrawable filter color (view-helper/index.android.ts).setDrawableColor/getDrawableColorare static helpers that take aDrawableand have no owner to hang state on.getDrawableColorhas no callers in core or in the plugins I checked.- Activity registry (
ui/frame/activity-callbacks-store.ts). The embedded host activity is a plain Java object, andsetActivityCallbacksruns before anyNativeWindowexists for it, so there is no JS owner yet. The registry also replaces the'isNativeScriptActivity' in activityprobes, which otherwise touched every activity in the process, including third-party ones.
Both are keyed by the JS wrapper, and a WeakMap entry does not survive a wrapper rebuild (the canary mirror for expandos does). For the activity registry, setActivityCallbacks therefore pins an embedded host activity in a strong set until its onDestroy, so its wrapper and entry can't be dropped mid-lifecycle; extended activities need no pin. If a host never delivers onDestroy, that one activity stays pinned. The drawable map is not pinned: losing an entry only makes getDrawableColor return an empty color for that drawable, and nothing in core calls it.
Open questions
defaultPaddingsread fallback.view-base/index.tsstill readsnativeView.defaultPaddingswhen the per-class cache misses. At least one published plugin pre-seeds it on a native object that is not anandroid.view.View(anandroid.view.MenuItem), so thatViewHelper.getPaddingis never called on it. Removing the read would crash that plugin. Core no longer writes it; should the read be replaced by a proper hook (e.g. an overridable method)?isNativeScriptActivitynow means "has calledsetActivityCallbacks". Core's own activities, and custom activities following the documented pattern, both set the flag and callsetActivityCallbacks, so nothing changes for them. A custom activity that callssetActivityCallbackswithout setting the flag is now treated as a NativeScript activity (it wasn't before). A custom activity that assignsthis._callbacksby hand without callingsetActivityCallbackswould no longer be found by core.activity.isNativeScriptActivityis still set oncom.tns.NativeScriptActivityfor anyone reading it.- Embedded host activity. The
com.tns.embedding.*Java classes are not in this repo, so I treated the host activity as plain (it is a native app's activity). If an embedding host can be JS-extended, the registry still works; it is just not required. - Removed exports.
ui/frame/index.android.tsexported a module-levelattachStateChangeListenersingleton (each Frame now owns its listener), andui/utils.d.tsexportedNativeScriptAndroidView. Neither is in the public barrel and nothing in this repo or the plugins I checked uses them, but a deep import would break. - Embedded host activities no longer carry
isNativeScriptActivity/_callbacks. The registry getters (ui/frame/activity-callbacks-store) are internal and not exported from@nativescript/core. A plugin that read those properties off an embedded host activity has no public replacement. Should the getters be exported?
Testing
Re-run after rebasing onto main (8a6f0ca ):
npx nx run core:test: 59 files, 672 passed, 1 skipped (same asmain).open-window.android.spec.tsnow registers its mock NativeScript activities through the activity registry instead of settingisNativeScriptActivity.tsc -p packages/core/tsconfig.lib.json --noEmit: clean.- ESLint on the changed files: no new findings. The one existing error (
prefer-constonTransitionListenerinfragment.transitions.android.ts) is on an unchanged line. apps/automatedbuilds for Android (ns build android). The on-device suite has not been run yet. The shared emulator I had available was cold-restarted mid-attempt, stayedoffline, and was later shut down. The suite needs to pass on an emulator before this leaves draft.
No new unit tests: the changed code needs real native objects, which the Vitest mocks don't provide. The apps/automated suite covers these widgets.
nx-cloud
Bot
commented
Nov 22, 2026
·
edited
Loading
Copy link Copy Markdown
🤖 Nx Cloud AI Fix Eligible
To disable these notifications, a workspace admin can disable them in workspace settings. View your CI Pipeline Execution ↗ for commit d04b85f
💡 Dealing with memory or CPU issues? See memory and CPU details with the resource usage add-on ↗ . ☁️ Nx Cloud last updated this comment at |
pkg-pr-new
Bot
commented
Nov 22, 2026
·
edited
Loading
Copy link Copy Markdown
commit: |
View reviewed changes
edusperoni added 2 commits November 22, 2026 16:19
refactor(android): keep state for plain native objects in JS
e736f9a
Core stored JS properties on plain (non-extended) Java objects: listener back-references on native views, the cached default background drawable, default paddings, the SeekBar owner, a Frame's attach-listener owner, animator transition data, and activity callbacks/flags on embedded host activities. Runtimes where a plain object's JS wrapper can be dropped and rebuilt lose that state or pay to mirror it. Keep the state on the owning JS objects instead: View fields for listeners and the default background, per-owner listener instances for Slider, Frame and fragment animators, and an activity registry for activity callbacks. Expandos on extended objects (NativeScriptActivity, FragmentClass, TabHostImpl, listener implementations) are unchanged.
refactor(android): pin embedded host activities until onDestroy
29c8cfd
The activity registry is keyed by the JS wrapper. A plain host activity has no other JS owner between onCreate and onDestroy, so a collected and rebuilt wrapper would lose its callbacks mid-lifecycle. Hold it strongly until onDestroy.edusperoni force-pushed the refactor/android-native-object-state branch from
bf061b8 to
29c8cfd
Compare
November 22, 2026 19:19
Merge branch 'main' into refactor/android-native-object-state
d04b85f
This branch has not been deployed
No deployments
Sign up for free to join this conversation on GitHub . Already have an account? Sign in to comment