Repository navigation
refactor(android): keep state for plain native objects in JS - #11664
Draft
edusperoni wants to merge 3 commits into
Draft
edusperoni wants to merge 3 commits into
edusperoni wants to merge 3 commits into
Conversation
|
| Command | Status | Duration | Result |
|---|---|---|---|
nx test apps-automated -c=android |
❌ Failed | 3m 34s | View ↗ |
nx run-many --target=test --configuration=ci --... |
✅ Succeeded | <1s | View ↗ |
💡 Dealing with memory or CPU issues? See memory and CPU details with the resource usage add-on ↗.
☁️ Nx Cloud last updated this comment at 2026-11-28 00:51:07 UTC
commit: |
farfromrefug
approved these changes
Nov 22, 2026
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.
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
November 22, 2026 19:19
bf061b8 to
29c8cfd
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

PR Checklist
apps/automatedon device not yet run): https://github.com/NativeScript/NativeScript/blob/master/tools/notes/DevelopmentWorkflow.md#unit-testing.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
SeekBarowner, 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:
nativeViewProtected), the cached default background, and the ListView search wrapper.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.Teardown is unchanged: listeners still get
owner = nullindisposeNativeView, and their View fields are released. No changes to the public barrel API.ui/utils.d.tsdrops the exportedNativeScriptAndroidViewtype, which only declared the_cachedDrawableexpando (see Open questions).Inventory
Line numbers are on
mainat this PR's original base (b1fdbd5) and have shifted slightly since; paths are relative topackages/core/.Already done on
main(dropped from this PR when it was rebased):editTextand TabView'sviewPager/tabLayout/viewPager.adapteroff the native views onto View fields.WeakRef. TheclickListener/menuItemClickListenerexpandos on the native views are still onmain, so this PR still moves them to View fields, typed for the weak owner.TransitionListener. This PR's fragment change covers theAnimatorlisteners only.Plain objects (changed)
ui/core/view-base/index.ts:1233,1237-1238defaultPaddingswritesDEFAULT_VIEW_PADDINGScache already holds the value. The read fallback at:1230stays (see Open questions).ui/core/view/index.android.ts:1666,1693,1755-1762_cachedDrawableView._cachedDrawable, paired with the native view it was captured from, so a swapped native view (setNativeView) recaptures its default. Reset indisposeNativeView.ui/core/view/view-helper/index.android.ts:24,38,50_backgroundColorDrawable(fromgetBackground()etc.)WeakMap<Drawable, number>(no JS owner)ui/button/index.android.ts:81,86clickListenerandroid.widget.ButtonButton._clickListener(the listener's owner is already weak since #11658)ui/switch/index.android.ts:51,57listenerandroid.widget.SwitchSwitch._checkedChangeListenerui/image/index.android.ts:79,84listenerorg.nativescript.widgets.ImageViewImage._imageLoadedListenerui/date-picker/index.android.ts:78,95listenerandroid.widget.DatePickerDatePicker._dateChangedListenerui/time-picker/index.android.ts:54-55listener,calendarandroid.widget.TimePickercalendaris a localui/editable-text-base/index.android.ts:115,122-126listenerandroid.widget.EditTextEditableTextBase._editTextListenersui/search-bar/index.android.ts:154,158,164,167queryTextListener/closeListenerandroidx.appcompat.widget.SearchViewSearchBar._queryTextListener/_closeListenerui/action-bar/index.android.ts:176,181menuItemClickListenerandroidx.appcompat.widget.ToolbarActionBar._menuItemClickListener(the listener's owner is already weak since #11658)ui/web-view/index.android.ts:119,126-127clientandroid.webkit.WebViewWebView._webViewClientui/list-view/index.android.ts:166,170,184,187adapter/itemClickListenerandroid.widget.ListViewListView._listViewAdapter/_itemClickListenerui/list-view/index.android.ts:767and 10 reads,_searchView._wrapperandroid.widget.SearchViewListView._searchViewWrapper(not in the earlier sweep)ui/list-picker/index.android.ts:113-121,133-137,146-148formatter/valueChangedListenerandroid.widget.NumberPickerListPicker._formatter/_valueChangedListener.editText→_editTextis already onmain(#11661).ui/tab-view/index.android.ts:544,548,551,573-578viewPager/tabLayout/viewPager.adapterGridLayout,TabViewPagermain(#11661); no longer in this PRui/slider/index.android.ts:29,68,75seekBar.ownerread by a shared listenerandroid.widget.SeekBarWeakRef<Slider>ui/frame/index.android.ts:48,54,502,516view[ownerSymbol]read by a shared attach listenerContentLayoutWeakRef<Frame>. Removed indisposeNativeView.ui/frame/fragment.transitions.android.ts:259-286,303-336,357-362animator.entry/transitionTypeAnimatorfromcreateAndroidAnimatorAnimatorListenerper animator, holding the entryWeakRefand type. Exit/popEnter listeners are kept on the entry so they can be removed.animator.backEntrywas read but never written, so it is nowundefinedexplicitly.ui/frame/activity.android.ts:80-86and the embedded callbacks,isNativeScriptActivity/_callbacksui/frame/activity-callbacks-store.ts, WeakMap)ui/frame/index.android.ts:1186-1192_callbacks/_onBackPressedinsetActivityCallbacksactivity._callbacksis 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 andinprobesgetActivityCallbacks()/isNativeScriptActivity()from the registryExtended or JS objects (unchanged)
ui/frame/activity.android.ts:23-66this.isNativeScriptActivity/this._callbackscom.tns.NativeScriptActivityis.extend()-edactivity._callbackswritten bysetActivityCallbacksoutside embedded mode@NativeClassactivities, and the documented custom-activity pattern readsthis._callbacksui/frame/fragment.android.tsthis._callbacks,frame-helper-for-android.ts:49,358,ui/frame/index.android.ts:279fragment[CALLBACKS]com.tns.FragmentClassis extendedui/segmented-bar/index.android.ts:232,240nativeView.listenerTabHostImpl(@NativeClass)callback['_activity'](frame),callback['_dialog'](view),.owneron listener instances,_pagerAdapter.items@NativeClass/.extend()instanceshttp/http-request-internal/index.android.ts:128Object.assign(content, …)contentis a JS object literaljavaOptions.*(http),lp.gravity/lp.weight/lp.row/ flexbox and docklp.*,Utils.ignoreEdgeToEdgeOnOlderDeviceslp.weightis only written when the read returned a number, i.e. a realLinearLayout.LayoutParams.weight'setOverflowEdge' in nativeView(view)args.view._listViewItemIndex,view['_lastText'](a11y helpers),nativeWindow._surfaceGone,itemSpec.ownerWeakMap / 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.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,
setActivityCallbackstherefore pins an embedded host activity in a strong set until itsonDestroy, so its wrapper and entry can't be dropped mid-lifecycle; extended activities need no pin. If a host never deliversonDestroy, that one activity stays pinned. The drawable map is not pinned: losing an entry only makesgetDrawableColorreturn 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.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.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.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.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/automatedsuite covers these widgets.