Important changes since 1.12.0:
ComponentActivitynow implements theOnPictureInPictureUiStateChangedProviderinterface which means it can now integrate with the newcore:core-pipartifact that allows allow any component to receive picture-in-picture ui state change events.EdgeToEdgeis now re-invoked on configuration changes to ensure that the system status bar color is properly updated.
New Features
- Dropped support for x86 based Mac and iOS KMP targets
API Changes
- Added
RequiresFlagannotation for code that must be gated on pre-release flag checks I77bba b/479114442 - Adds
ANNOTATION_TYPEtarget toRequiresApiandRequiresExtensionI0cb0d - Projects released with Kotlin 2.0 require KGP 2.0.0 or newer to be consumed Idb6b5 b/344563182
- Updated
@Discouragedretention policy. Id2f85 b/375937557
New Features
- Added support for Parcelable (s) besides
PendingIntentI8ab9f - APIs to convert from/to Platform request and response Ifdf20,
API Changes
- Parameter conformity with styleguide. I69b2d
- Add APIs to convert from/to Platform request and response Ifdf20 b/476047880
- Rename
AppFunctionManagerCompattoAppFunctionManager. Id9a78 b/448372122 - Remove get/set APIs for
PendingIntent. Ic7fd6 b/447530985 - Add support for Parcelables and migrate
PendingIntentto be represented as a Parcelable. I8ab9f b/447530985
Bug Fixes
- Moves libraries to use Java 11 target. This means produced bytecode will be Java 11 (class file version 55) and might require desugaring to use the library If4c2a b/457821470
API Changes
- Added
JvmOverloadstoPowerMetric.EnergyandPowerMetric.PowerIac0d0 b/481371562.
Bug Fixes
- Updated
ArtMetricto account for top-level packages, especially important when using AGP/R8 9.1+, or-repackageclassesglobal option. Previously,ArtMetricwould fail to detect these classloads in itsartClassLoad...measurements. I207ca b/487402058
API Changes
- Exposed the
CameraController.setSessionConfig()API. This allows providing a customSessionConfigfor advancedUseCaseconfigurations not directly exposed byCameraController. When aSessionConfigis active, other configuration methods onCameraControllerare disabled.I35cf1 b/448525636
Bug Fixes
- Moves libraries to use Java 11 target. This means produced bytecode will be Java 11 (class file version 55) and might require desugaring to use the library If4c2a b/457821470
- Fixed a bug in
ImageAnalysiswhere images were not correctly rotated when output image rotation is enabled and the initial relative rotation is 0 degrees. Id46c2 b/487160584
Important changes since 1.5.0:
- Added no-argument version of trim for
MutableFloatList,MutableDoubleList,MutableIntList. - Add
toMutableOrderedScatterSet,toOrderedScatterSet,toMutableScatterMap,toScatterMap,toMutableScatterSet,toScatterSetextension functions. - Performance improvements for
ScatterMapandScatterSet. minSdkversion is now 23.
Bug Fixes
- Fix
isTransitionActiveso that it only reports true when there’re active animation from matched shared element d3426a b/474385510
Bug Fixes
- Fixed an
IndexOutOfBoundsExceptioninBasicTextFieldwhen usingOutputTransformationand deleting text. I20ee1
API Changes
- Optimized
BasicTextField's internal min size calculations. These are controlled byComposeFoundationFlags#isBasicTextFieldMinSizeOptimizationEnabled, should you need to disable them. I70ade - Added
rememberUpdatedStyleStatewhich is part of the experimental Style API.rememberUpdatedshould be used when createing instances ofStyleStatewhen parameters of the composable component (such asenabled) are copied into the style state Idf7ff b/485510967 - Renames
PointerInputChangeandHistoricalChangeproperties for retrieving scale and pan values. I989a8 b/481333653 - Adds more functionality for trackpad testing APIs, to simulate different curves and inputs for a trackpad gesture. I290fb b/473603145 b/479213358
- Splits the new
PointerEventType.Panand intoPointerEventType.PanStart,PointerEventType.PanMoveandPointerEventType.PanEnd. Similarly,PointerEventType.Scaleis split intoPointerEventType.ScaleStart,PointerEventType.ScaleChangeandPointerEventType.ScaleEnd. This split allows passing through additional information about the start and end of platform-interpreted pan and scale gestures, which then allows pointer input handlers in Compose to use this information to detect events appropriately, and especially know when a pan or scale is done. I4daf6 b/479285849 b/481333653 - Added
constraintstoGridConfigurationScopeto allow defining grid tracks based on the available size. I80a41 b/481205205 b/481205205 - The
FlexBoxDSL now uses functions (e.g., grow(1f)) instead of properties (e.g., grow = 1f) for configuration withinFlexBoxConfigand Modifier.flex. I8dbae b/475491619
Bug Fixes
- Fixed a bug where
OutputTransformationcauses duplicate character insertion on some IMEs. I9fdc0 - Adds fling support to trackpad scrolling gestures I55f8a b/479285849
- Add benchmarks for the experimental Style API I67437
External Contribution
- Add a
InputTextSuggestionStateproperty to help identify the different states a transliteration input can be in when text replacement suggestions are available. Also introducesTextCompositionRangeto track the range of the current transliteration text composition range; a null value indicates no composition in place. I7a67f b/476472318 - Added a new overload to
BasicTooltipBoxthat allows configuringpropagateMinConstraints, similar to Box's parameter with the same name. This allows passing the minimum constraints directly to the children of theBasicTooltipBox, without them being relaxed byBasicTooltipBox. Thanks Steven Schoen! Ib145f b/467532639 b/301605744
API Changes
SnapshotFlowManagerand the overload ofsnapshotFlowthat accept themanagerparameter are now marked as experimental I5c1a5 b/486077876 I0de71 b/486077876
Bug Fixes
- Fix "Apply is called on deactivated node" crash in pausable composition I880c0 b/484300733
- Fixed an issue in the
LinkTablethat could causeArrayIndexOutOfBoundsExceptionsor metadata corruption when usingMovableContent. I8452b - Fixed an issue in the
LinkTablethat would prevent diagnostic traces from being populated correctly I59868 - Fixed an issue in the new SlotTable where
RememberObserversused inMovableContentcould cause anOutOfMemoryError/infiniteloop when removed. I884e7
API Changes
- Support for custom
windowTokenhas been added to Jetpack Compose Dialog Ic7728 - Support for custom
windowTokenandwindowTypehas been added to Jetpack Compose Popups. I0a04f - Introduce
PreviewWrapperinterface and an annotation provider. This will allow developers to seamlessly wrap their previews with custom behavior. I29f54 b/484306729 - When
AndroidComposeUiFlags.isSharedFontEnabledis true, font-related object instances, likeFontLoaderandFontFamilyResolver, can be shared acrossComposeViewinstances insideComposeViewContext. I403e8 - Compose semantics processors will use view.handler instead of the
mainLooper, avoiding crashes in views that use non-main handlers. I671c3 b/486235925 - Added a
isSkipNonImportantSemanticsNodesHitTestEnabledflag that guards a bug fix for semantics hit testing, which affectsTalkBack's touch-to-explore. I2933f b/481011169 b/454377558 b/461360154 - Support for displaying Jetpack Compose Dialogs from Android Services has been added. By providing a custom window type through the new
windowTypeparameter inDialogProperties, developers can now show Dialogs in overlay windows. I7c504 b/478214962 - Renames
PointerInputChangeandHistoricalChangeproperties for retrieving scale and pan values. I989a8 b/481333653 - Adds more functionality for trackpad testing APIs, to simulate different curves and inputs for a trackpad gesture. I290fb b/473603145 b/479213358
- Splits the new
PointerEventType.Panand intoPointerEventType.PanStart,PointerEventType.PanMoveandPointerEventType.PanEnd. Similarly,PointerEventType.Scaleis split intoPointerEventType.ScaleStart,PointerEventType.ScaleChangeandPointerEventType.ScaleEnd. This split allows passing through additional information about the start and end of platform-interpreted pan and scale gestures, which then allows pointer input handlers in Compose to use this information to detect events appropriately, and especially know when a pan or scale is done. I4daf6 b/479285849 b/481333653 - When
AndroidComposeUiFlags.isSharedHapticsEnabledis true,ComposeViewContextcontains the shared haptics controller instance. Icd79a - Introduced experimental
mediaQuery,derivedMediaQueryandUiMediaScopeAPIs (marked as@ExperimentalMediaQueryApi) to enable declarative adaptive UI development based on window dimensions, window posture, and other device and environment capabilities. I2d21e b/479800750
Bug Fixes
- Fixed an issue where the block-scoped
Modifier.dropShadowandModifier.innerShadowwould not redraw when the Shape parameter was dynamically changed. Ida262 b/486202623 - Fixed a bug that causes an inline content to be misplaced in RTL layouts with LTR text or LTR layouts with RTL text. I09789
- Fixes a bug where a
ComposeViewis used in a fragment transition, an exception was being thrown. Ia425f b/484100557
External Contribution
- Add a
InputTextSuggestionStateproperty to help identify the different states a transliteration input can be in when text replacement suggestions are available. Also introducesTextCompositionRangeto track the range of the current transliteration text composition range; a null value indicates no composition in place. I7a67f b/476472318
Important changes since 1.17.0:
compileSdkchanged from API 36 to API 36.1- Added
NotificationCompat.ProjectedExtenderto support notifications on projected devices. - Added
PictureInPictureUiStateCompatto help handle API differences for picture-in-picture feature - Added
AccessibilityNodeInfoCompat.SelectionCompatto help handle accessibility selection on devices running API 36.1
- Deprecate
credentials:credentials-e2eeI876f5 b/467132523
No changes
- This release introduces minor infrastructure bug fixes and does not include any DataStore API or behavior changes from version 1.2.0.
New Features
- Encryption Support: Introduced the new
androidx.datastore:datastore-tinkartifact which provides support for encryption of your datastore using the Tink library. This module introduces theAeadSerializer, which is a new wrapper class that implementsSerializer<T>and uses Tink’s Authenticated Encryption with Associated Data (AEAD) to encrypt and decrypt data. TheAeadSerializeris available to use in JVM and Android target platforms. - New
DataStoreBuilder API: IntroducedDataStore.Builder<T>as the scalable alternative toDataStoreFactory. With this new API, users now have a way to provide their own corruption logic viasetCorruptionHandler. In addition, theBuilderAPI requires that aDataStoreis initialized using aCoroutineContextinstead of aCoroutineScope, an improvement for structured concurrency, as it allows callers to define execution behavior (like specific Dispatchers) without forcingDataStoreto inappropriately manage or be bound by the lifecycle of the caller's scope.Note: We recommend all users to migrate from
DataStoreFactoryto the newDataStore.BuilderAPIs. By requiring aCoroutineContextinstead of aCoroutineScope, the API enforces better structured concurrency. This ensures DataStore operations are not bound to short-lived UI lifecycles (e.g.,viewModelScope), preventing premature cancellation and potential data loss.Warning: Ensure that the
CoroutineContextprovided to the Builder has aJob, and that it is application-scoped. If the context is canceled,DataStore's internal operations will be terminated prematurely.
API Changes
Introduced the new
androidx.datastore:datastore-tinkartifact forDataStoreencryption support. Ic106d b/167697691To encrypt data using Tink, follow these steps:
Create a key using Tink APIs:
val keysetHandle = AndroidKeysetManager.Builder() .withSharedPref(applicationContext, "keyset", "keyset_prefs") .withKeyTemplate(KeyTemplate.createFrom(PredefinedAeadParameters.AES256_GCM)) .withMasterKeyUri("android-keystore://master_key") .build() .keysetHandleCreate an
AeadSerializerthat wraps an existing serializer:val aeadSerializer = AeadSerializer( // Use tink APIs to create an Aead object to encrypt/decrypt data. aead = keysetHandle.getPrimitive( RegistryConfiguration.get(), Aead::class.java, ), // AeadSerializer can wrap an existing serializer. wrappedSerializer = ExistingSerializer, // Specify a unique name to prevent a ciphertext swapping attack. associatedData = "settings.json".encodeToByteArray(), )Use this
aeadSerializerin place of your serializer when creating the datastore instance:val dataStore = dataStore( fileName = "settings.json", serializer = aeadSerializer, scope = scope, )
Introduced
DataStore.Builder<T>as the modern, scalable alternative toDataStoreFactory. I3b110 b/267785821 b/400507108 b/368385681 b/427722902 b/370838564 b/167697691
API Changes
- We have added
WearWidgetBrushAPI with thecolormethod to be used for the Wear Widget background. I66f54 b/464273091 fetchActiveWidgetsForProvidermethod has been removed as there is alreadyfetchActiveWidgets. I85e4e b/486197890
API Changes
- Replaced
TitleChipDefaults.contentPaddingwith aContentPaddingconstant. If992f b/489451530 - Glimmer
ListStatenow providesScrollIndicatorStateI0a2f8 b/481662773 - Added a new
TextStylecalledcaption. For the existingTextStyles, UpdatedfontWeight,fontSizeandlineHeight. I2319f b/473560419
New Features
- Assorted small bug fixes
API Changes
- Add
InProgressShape.isCanceled, fix concurrency issues in authoring module. Ibfd32 b/474385518 b/470695777 - Expose zero-argument version of
CanvasStrokeRenderer.createandInProgressStroke.updateShapeto Java Id80a1 b/457715938
Bug Fixes
Bug Fixes
- Moves libraries to use Java 11 target. This means produced bytecode will be Java 11 (class file version 55) and might require desugaring to use the library If4c2a b/457821470
- This library now uses JSpecify nullness annotations, which are type-use. Kotlin developers should use the following compiler argument to enforce correct usage:
-Xjspecify-annotations=strict(this is the default starting with version 2.1.0 of the Kotlin compiler) Ieee48 b/326456246
Scoped ViewModels
This release introduces APIs to create scoped
ViewModelStoreinstances in Compose. This allowsViewModelsto be tied to specific UI scopes (such as individualPagerpages orLazyListitems). TheseViewModelssurvive configuration changes and are automatically cleared when their corresponding Composable is permanently removed from the hierarchy.// Hoist the parent provider outside the Pager. val provider = rememberViewModelStoreProvider() val pagerState = rememberPagerState(pageCount = { 5 }) HorizontalPager(state = pagerState) { page -> // Create an owner scoped to the current page. val storeOwner = rememberViewModelStoreOwner(provider, key = page) // Provide the scoped owner to this composition. CompositionLocalProvider(LocalViewModelStoreOwner provides storeOwner) { // ViewModel is now scoped specifically to this page. val viewModel: PageViewModel = viewModel() } }
Note that ViewModelStoreProvider is available outside of Compose and can be used with Activities, Fragments and/or Views.
New Features
- Add support for all KMP targets to ViewModel Navigation3. I60fa5
- Add factory functions for
LifecycleOwner,ViewModelStoreOwner, andSavedStateRegistryOwnerto reduce boilerplate when composing custom owner components. I9682c - Add a lambda-based
Lifecycle.addObserverextension function to allow observing lifecycle events without instantiating an anonymous object. I94f38 - Add
defaultViewModelProviderFactoryanddefaultViewModelCreationExtrasextensions toViewModelStoreOwner. These provide safe access to defaults without requiring manual type checks againstHasDefaultViewModelProviderFactory. Ifa83d
API Changes
- Add
rememberViewModelStoreOwnerto easily create scopedViewModelStoreOwners in Compose. This function returns an owner that is tied to the Composable's lifecycle, automatically clearing its ViewModels when the Composable is removed from the UI. I2a15b b/165642391 - Add
rememberViewModelStoreProviderto allow creating scopedViewModelStoreinstances in Compose. This function links a child store to a parent owner, ensuring ViewModels survive configuration changes while automatically clearing them when the Composable is removed from the hierarchy. I0f57a b/165642391 - Add
ViewModelStoreProviderto manage scopedViewModelStoreinstances. This class enables the creation of child scopes that survive configuration changes but can be independently cleared. It also providesViewModelStoreOwnerwrappers that inherit default factories and creation extras from the parent. I87f4f b/434651920
New Features
NavHostnow provides an overload that acceptspredictivePopEnterTransitionandpredictivePopExitTransitionparameters to allow for custom transition during the predictive back gesture. Iac9b0 b/478294569
Min SDK Update
- The default minSdk has been from API 21 to API 23 along with the rest of the AndroidX libraries. Ibdfca b/380448311 b/435705964 b/435705223
External Contribution
No changes
- This release does not have any api or behavioral change from version 3.4.1.
New Features
The
paging-commonartifact now contains a newasStateflow operator onFlow<PagingData>to convert it into aFlow<ItemSnapshotList>. This unlocks capabilities such as:- combine Flow of
ItemSnapshotListwith other data sources - share flow with multiple collectors without
cachedIn - cache paged data locally
- modify paged data in memory
- expose paged data as part of a UI state
// In your ViewModel val pager = Pager(pagingConfig, pagingSourceFactory) val pagerFlow = pager.flow.asState() // alterantively convert the flow to a SharedFlow val pagerFlow = pager.flow.asState().stateIn() // In presenter layer val snapshotFlow = viewModel.pagerFlow.collectAsStateWithLifecycle(initialList) val snapshot = itemsFlow.value LazyColumn { items(items = snapshot.items) { ... } }- combine Flow of
The
paging-commonartifact has also addedPager.appendandPager.prependAPIs to manually trigger loads at either edge of loaded items.- When used with
paging-runtimeorpaging-compose, provides an alternative to load more data besides scrolling - When used with the new
asStateAPI, it is the only way to load more data
LazyColumn { item { /** * Load more items when users scroll near the top of loaded items. */ LaunchedEffect(viewModel) { viewModel.prepend() } } items(snapshot.items) { item -> Text("Item: $item") } item { /** * Load more items when users scroll near the bottom of loaded items. */ LaunchedEffect(viewModel) { viewModel.append() } } }- When used with
Added
Pager.refreshandPager.retryto recover from load errors when usingasStateAPI. See this document for more sample usages of the new APIs. I1e1e9 If3c87 Idbd48 Id1e1d I816fe
API Changes
- Added Android SDK Extension Version 19 as requirement for
ImageSelectionFeature I93af7 - Marked
isLinearized Booleanas deprecated and replaced withlinearizationStatus IntDefI5c1bf
Bug Fixes
- Fix fast scroller rendering without text on single tap gesture for
PdfViewercompose component I442b7 - Clicking on the center of the widget center for
clickTypeWidgets.Ie5661 - Moves libraries to use Java 11 target. This means produced bytecode will be Java 11 (class file version 55) and might require desugaring to use the library If4c2a b/457821470
New Features
- Add a new experimental operation for
TextStyle.TextStyleenables commonly used typography styling to be written to the document once, and reused by several text runs bfc6487
API Changes
- Expose
RemoteTextStylemerge I971ce b/446824085 - Expose
RemotePainteras public API I252c1 b/446824085 - Expose
Border/ClipModifiers andRemoteShape. Id26dd b/446824085 - Expose
RemoteColorAPIs inremote-creation-composeI4ab00 b/446824085 - Expose
RemoteTextAPI I6b019 - Expose
RemoteImageAPI Ided31 - Expose
RemoteBoolean,RemoteString, andRemoteFloatAPIs Id9ee6 - Remote Composable from
WidthInannotation I80784
Bug Fixes
- Moves libraries to use Java 11 target. This means produced bytecode will be Java 11 (class file version 55) and might require desugaring to use the library If4c2a b/457821470
- Ensure length and textlookup update correctly. Previously the length of
RemoteStringswould be calculated on the first frame, and not updated afterwards e49cb53 - Support
TextFromFloatfor numbers with large fractional components. Previously large "digitsAfter" values could result in the float evaluating to 0 5080bc54
- Ensure length and textlookup update correctly. Previously the length of
Room 3.0 (package androidx.room3) is a major version update of Room 2.x package (androidx.room) that focuses on Kotlin Multiplatform (KMP).
The core annotation APIs are kept the same along with the main components:
- An abstract class that extends
androidx.room3.RoomDatabaseand is annotated with@Databaseis the entry point for Room's annotation processor. - The database declaration has one or more data classes describing the database schema and are annotated with
@Entity. - Database operations are defined in
@Daodeclarations that contains query functions whose SQL statements are defined via the@Queryannotation. - At runtime, the database implementation can be obtained via a
RoomDatabase.Builderwhich is also used to configure the database.
Most of the documentation in the Save data in a local database using Room guide is still relevant to Room 3.0.
The major breaking differences between Room 2.x are as follows:
- New package,
androidx.room3. - SupportSQLite APIs are no longer supported, unless you are using the
androidx.room3:room3-sqlite-wrapper. - All database operations are now Coroutine APIs based.
- Kotlin code generation only.
- Kotlin Symbol Processing (KSP) is required.
Along with breaking changes, Room 3.0 brings in new functionality compared to 2.x:
- JS and WasmJS Support
- Custom DAO Return Types
New Package
To prevent compatibility issues with existing Room 2.x implementations and for libraries with transitive dependencies to Room (for example, WorkManager), Room 3.0 resides in a new package, which means it also has a new maven group and artifact ids. For example, androidx.room:room-runtime has become androidx.room3:room3-runtime and classes such as androidx.room.RoomDatabase will now be located at androidx.room3.RoomDatabase.
No SupportSQLite APIs
Room 3.0 is fully backed by the SQLiteDriver APIs and no longer references SupportSQLite types such as SupportSQLiteDatabase or Android types such as Cursor. This is the most significant change between Room 3.0 and 2.x since the RoomDatabase APIs that mirrored SupportSQLiteDatabase along with the API to get a SupportSQLiteOpenHelper have been removed. A SQLiteDriver is now required to build a RoomDatabase.
For example, APIs for direct database operations are replaced by driver equivalents:
// Room 2.x
roomDatabase.runInTransaction { ... }
// Room 3.x
roomDatabase.withWriteTransaction { ... }
// Room 2.x
roomDatabase.query("SELECT * FROM Song").use { cursor -> ... }
// Room 3.x
roomDatabase.useReaderConnection { connection ->
connection.usePrepared("SELECT * FROM Song") { stmt -> ... }
}
Callback APIs that had as argument a SupportSQLiteDatabase have also been replaced by their equivalent API that has a SQLiteConnection as argument. These are migrations callback functions such as Migration.onMigrate() and AutoMigrationSpec.onPostMigrate() along with database callbacks such as RoomDatabase.Callback.onCreate(), RoomDatabase.Callback.onOpen(), etc.
If Room was being used in a KMP project, then migrating to 3.0 is simpler as it mostly involves updating import references, otherwise the same migration strategy from Room in Android-only to KMP applies, see the Room KMP Migration Guide.
SupportSQLite Wrapper
Room 3.x preserves the SupportSQLite wrapper created in 2.x to ease migrations and is now located in a new artifact androidx.room3:room3-sqlite-wrapper. The compatibility API allows you to convert a RoomDatabase into a SupportSQLiteDatabase. Invocations of roomDatabase.openHelper.writableDatabase can be replaced by roomDatabase.getSupportWrapper().
Kotlin and Coroutines First
To better evolve the library, Room 3.0 only generates Kotlin code and is only a Kotlin Symbol Processor (KSP). Compared to Room 2.x there is no Java code generation and configuration of annotation processor via KAPT or JavaAP is no longer possible in Room 3.0. Note that KSP is able to process Java sources and the Room compiler will generate code for database, entities or DAOs whose source declarations are in Java. It is recommended to have a multi-module project where Room usage is concentrated and the Kotlin Gradle Plugin and KSP can be applied without affecting the rest of the codebase.
Room 3.0 also requires the use of Coroutines, and more specifically DAO functions have to be suspending unless they are returning a reactive type, such as a Flow or a custom DAO return type. Room APIs to perform database operations are also suspend functions, such as RoomDatabase.useReaderConnection and RoomDatabase.useWriterConnection.
As opposed to Room 2.x it is no longer possible to configure a RoomDatabase with an Executor, instead a CoroutineContext along with a dispatcher can be provided via the database's builder.
InvalidationTracker APIs in Room 3.0 are Flow based, InvalidationTracker.Observer is removed along with its relevant APIs addObserver and removeObserver. The mechanism to react to database operation is through Coroutine Flows that can be created via the createFlow() API in the InvalidationTracker.
Example usage:
fun getArtistTours(from: Date, to: Date): Flow<Map<Artist, TourState>> {
return db.invalidationTracker.createFlow("Artist").map { _ ->
val artists = artistsDao.getAllArtists()
val tours = tourService.fetchStates(artists.map { it.id })
associateTours(artists, tours, from, to)
}
}
Web Support
The Room 3.0 release adds JavaScript and WasmJs as KMP targets. Combined with the release of the SQLiteDriver interfaces (androidx.sqlite:sqlite) that also target JavaScript and WasmJs and a new driver WebWorkerSQLiteDriver located in the new artifact androidx.sqlite:sqlite-web, it is possible to use Room in common code that targets all major KMP platforms.
Due to the asynchronous nature of the web platforms, Room APIs that took SQLiteStatement as argument are now suspend functions. Example of these functions are Migration.onMigrate(), RoomDatabase.Callback.onCreate(), PooledConnection.usePrepared() and others. In the driver APIs the asynchronous APIs are common on all platforms and the synchronous are common for non-web targets. Therefore a project that does not target web can continue to use the synchronous APIs (SQLiteDriver.open(), SQLiteConnection.prepare() and SQLiteStatement.step()) in common code. Meanwhile a project that only targets web must use the asynchronous APIs (SQLiteDriver.openAsync(), SQLiteConnection.prepareAsync() and SQLiteStatement.stepAsync()).
For convenience the androidx.sqlite package also added suspend extension functions with the synchronous names of the mentioned APIs (with the addition of SQLiteConnection.executeSQL), these APIs are recommended when the project targets both web and non-web platforms since the APIs are expect / actual declarations that will call the right variant based on the platforms. These are the APIs Room's runtime use and enable driver usage in common code for all supported platforms.
Example usage:
import androidx.sqlite.executeSQL
import androidx.sqlite.step
roomDatabase.useWriterConnection { connection ->
val deletedSongs = connection.usePrepared(
"SELECT count(*) FROM Song"
) { stmt ->
stmt.step()
stmt.getLong(0)
}
connection.executeSQL("DELETE FROM Song")
deletedSongs
}
The WebWorkerSQLiteDriver is an implementation of a SQLiteDriver that communicates with a Web Worker for performing database operation off the main thread and enables storing the database in the Origin Private File System (OPFS). To instantiate the driver a worker that implements a simple communication protocol is required, the protocol is described in the WebWorkerSQLiteDriver KDoc.
Currently the WebWorkerSQLiteDriver does not ship with a default worker that implements the communication protocol, but as an example, the androidx codebase contains a worker implementation that can be used in your project. It uses SQLite's WASM and stores the database in OPFS. The example worker is published as a local NPM package and thanks to Kotlin's support for NPM dependencies, a small KMP module can be created to serve the worker.
See the following GitHub project demonstrating the usage of a local web worker for Room.
Once a worker is set up in the project, then configuring Room for the Web is similar to other platforms:
fun createDatabase(): MusicDatabase {
return Room.databaseBuilder<MusicDatabase>("music.db")
.setDriver(WebWorkerSQLiteDriver(createWorker()))
.build()
}
fun createWorker() =
Worker(js("""new URL("sqlite-web-worker/worker.js", import.meta.url)"""))
A future version of the Web driver might contain a default worker published in NPM, making the web setup simpler.
Custom DAO Return Types
Various DAO return type integrations such as those for RxJava and Paging have been transformed to use a new API in Room 3.0 called DAO return type converters. A DAO return type converter function (@DaoReturnTypeConverter) enables transforming the result of a DAO function into a custom type defined by the annotated function. These functions enable participating in Room's generated code that transforms query results into data objects. Classes that contain DAO return type converters have to be registered via the @DaoReturnTypeConverters annotations in the @Database or @Dao declarations.
For example, to have a DAO query return a PagingSource, the converter class located in androidx.room3:room3-paging must now be registered:
@Dao
@DaoReturnTypeConverters(PagingSourceDaoReturnTypeConverter::class)
interface MusicDao {
@Query("SELECT * FROM Song)
fun getSongsPaginated(): PagingSource<Int, Song>
}
Existing integrations have been moved to DAO return type converters:
| Return Type | Converter class | Artifact |
|---|---|---|
| PagingSource | PagingSourceDaoReturnTypeConverter | androidx.room3:room3-paging |
| Observable, Flowable, Completable, Single, Maybe | RxDaoReturnTypeConverters | androidx.room3:room3-rxjava3 |
| ListenableFuture | GuavaDaoReturnTypeConverter | androidx.room3:room3-guava |
| LiveData | LiveDataDaoReturnTypeConverter | androidx.room3:room3-livedata |
Like column type converters, DAO return type converters can be defined by the application. For example, an application could declare a @DaoReturnTypeConverter for the web type kotlin.js.Promise.
object PromiseDaoReturnTypeConverter {
@DaoReturnTypeConverter([OperationType.READ, OperationType.WRITE])
fun <T> convert(
db: RoomDatabase,
executeAndConvert: suspend () -> T
): Promise<T> {
return db.getCoroutineScope().promise { executeAndConvert() }
}
}
The above converter then allows DAO query functions to return Promise:
@Dao
@DaoReturnTypeConverters(PromiseDaoReturnTypeConverter::class)
interface MusicDao {
@Query("SELECT * FROM Song")
fun getAllSongs(): Promise<List<Song>>
}
A @DaoReturnTypeConverter function has a few requirements in the amount of parameter it must have and its types. The possible parameters are:
db: RoomDatabase: (Optional) Provides access to theRoomDatabaseinstance, which can be useful for performing additional database operations or accessing the coroutine scope.tableNames: Array<String>: (Optional) Contains the accessed tables of the query, useful for supporting observable / reactive types when combined with Room'sInvalidationTracker.createFlow()API.rawQuery: RoomRawQuery: (Optional) Contains at runtime an instance of the query, enabling transformations such as theLIMIT/OFFSETstrategy implemented by thePagingSourceDaoReturnTypeConverter.executeAndConvert: suspend () -> T: (Required) The Room generated function that will execute the query and parse its result into data objects.
For more information about the requirements for creating a DAO return type converter, see the KDoc on the @DaoReturnTypeConverter API.
New Features
- Enable generic serialization for
SavedStateobjects, allowing them to be encoded and decoded using standard formats like CBOR or JSON across all platforms. Iafda4 b/425919375
API Changes
- Add
putKotlinSerializableandgetKotlinSerializableextension functions toSavedStateWriterandSavedStateReaderto allow directly storing and retrieving Kotlin Serializable objects using keys, streamlining the integration withSavedStateAPIs. Iba02e - Add factory functions for
LifecycleOwner,ViewModelStoreOwner, andSavedStateRegistryOwnerto reduce boilerplate when composing custom owner components. I9682c - Enable saving and restoring
SnapshotStateSet(created viamutableStateSetOf()) withrememberSerializable. You can now useSnapshotStateSetinrememberSerializablewithout requiring a custom saver. I9a4ed b/449498367
New Features
- Add js and wasmJs targets to
androidx.sqlite:sqlitealong with asynchronous version of the driver APIs:SQLiteDriver.openAsync(),SQLiteConnection.prepareAsync()andSQLiteStatement.stepAsync(). - Existing projects that don't target web can continue using the synchronous APIs in common code, but once a project targets web then only the asynchronous APIs are available. For convenience the
androidx.sqlitepackage also includes top-level suspend functions that use the synchronous naming scheme (along withexecuteSQL) and are expect / actual declarations that will invoke the right variant based on the platform. It is recommended to use these APIs for common code targeting both web and non-web targets. - This release also includes a new artifact
androidx.sqlite:sqlite-webwhich containsWebWorkerSQLiteDriver, aSQLiteDriverimplementation for the web that communicates with a Web Worker to perform database operation via a simple messaging protocol. The protocol is documented in theWebWorkerSQLiteDriverand even though there is no default worker implementation with the artifact, one can be provided via the constructor. For a more concrete example on how this new artifact can be used, check out the Room 3.0 release notes.
Bug Fixes
- Fixed
UiObject2#scrollToElementOrNullthrowing instead of returningnull, and updated its return type If0109 b/479892735
API Changes
- Added an experimental
InMemoryRingBufferTraceSinkimplementation which allows setting a capacity restriction and avoids writing to disk unless explicitly asking for it. I1dc44 b/484409653 I65a37 b/484409653 - Fix race condition when emitting trace events for coroutine suspends and resumes. Ie145e
Bug Fixes
androidx.tracingno longer attempts to draw connections from parent to child coroutines in traces by default. This has been confusing, since the underlying trace format doesn't support1:NandN:1connections, resulting in a nest of arrows due to ambiguity about which coroutine slice connects to what. You can still manually opt-in to propagation with thetokenForManualPropagation()API when it's important for your use case. Ib2cf9
API Changes
- Projects released with Kotlin 2.0 require KGP 2.0.0 or newer to be consumed Idb6b5 b/344563182
API Changes
- Projects released with Kotlin 2.0 require KGP 2.0.0 or newer to be consumed Idb6b5 b/344563182
External Contribution
androidx.compose.ui.graphics.NativePainttypealias is deprecated, useandroid.graphics.Paintdirectly instead I6303c b/477394763- Replace
Paint.asFrameworkPaint()toPaint.nativePaintextension to avoid exposing platform type intocommonMainsourceset viatypealiasI6303c b/477394763
- This release updates the Compose for Wear OS 1.6.0 version to a release candidate, but there are otherwise no significant changes from the 1.6.0-beta01 release.
API changes
- Starting from API 36, accessing heart rate data, such as via
ProtoLayoutExpressions library withPlatformHealthSources.heartRateBpmandPlatformHealthSources.heartRateAccuracyneedsandroid.health.connect.HealthPermissions.READ_HEART_RATEpermission to be granted to the calling App.
New Features
- Added new Web Performance Metrics APIs
onFirstContentfulPaintMillis,onLargestContentfulPaintMillisandonPerformanceMarkMillistoNavigationListener. These APIs allow developers to track First/Largest Contentful Paint and performance marks directly in their app instead of using JavaScript to retrieve them. Idb93b b/432696062 - Added error information to the Navigation object, see
Navigation#getWebResourceErrorandWebResourceError#getDebugCode.If a navigation load fails due to a net error, error information about why this occurred is now available on the navigation object. I18bdc b/474625648 - Update the API shape of
BackForwardCachesettings by a newBackForwardCacheSettingsobject that can be obtained by callingWebSettingsCompat#getBackForwardCacheSettings, and can be used to alter each setting through set/get methods.
Note: We are removingWebSetingsCompat#setBackForwardCacheSettingsandBackForwardCacheSettings.Builder, so this change may cause compilation errors when you update to this version if you were using the removed API. I377f4 - Add an api to attch debug information to prefetch request. Ibb300 b/474559983
API Changes
- The minimum supported SDK (minSdk) has been increased to 24. Apps targeting SDK versions below 24 will need to update their target SDK to use this and future versions of the library. I4df32 b/452708695
- Removed the experimental
Profile#clearPrefetchAsyncsince it was no-op. This was in-development functionality that never worked. If you need to clear the cache, please submit a feature request. I341a4 b/483043529 - Migrate
androidx.webkit.OutcomeReceiverCompatto stable status, and renamed it toWebViewOutcomeReceiver. This library-specific copy of the interface allows thewebkitlibrary to maintaincompileSdk = 33, and the new name prevents name clashes. I0ebf7 I6ef8a b/487934754 - Changed return type of
StartUpLocation.getStackInformation()fromStringtoThrowableto allow apps to process the information better. I938d6 b/417434566
External Contribution
- Introducing new APIs to
- Inject persistent JavaScript as part of the document loaded event. This works similar to the existing
WebViewCompat#addDocumentStartJavaScript, but ensures that the DOM is ready when the script runs. The new API isWebViewCompat#addJavaScriptOnEvent. - Inject JavaScript and
WebMessageListeners into isolated worlds, to prevent collisions with existing page JavaScript. The new APIs areWebViewCompat#addJavaScriptOnEventandWebViewCompat#addWebMessageListener. - Execute JavaScript as response to a web message sent from a page in the same frame/world combo that sent the message. The new API is
JavaScriptReplyProxy#executeJavaScript. I45d92 b/483103617
- Inject persistent JavaScript as part of the document loaded event. This works similar to the existing