New Features
AppState StateStore is a new library built on the Compose runtime that acts as a wrapper to provide custom integrations. The androidx.appstate.statestore artifact provides the library APIs and it also comes with a androidx.appstate.statestore:statestore-datastore artifact for state persistence. Developers can use StateStore to hoist their snapshot state into their application layer and the datastore integration to persist that state.
class MyApplication : Application() {
val stateStore = StateStore()
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
override fun onCreate() {
super.onCreate()
scope.launch {
// Start the listener in a child coroutine so it doesn't block the outer scope
launch {
try {
stateStore
.syncToDataStore(dataStoreFile("settings").absolutePath, this)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
}
New Features
AppState Transform is a new library built on the Compose runtime that allows for running a composition outside of your UI. The androidx.appstate.transform:transform artifact provides the library APIs and it also comes with a androidx.appstate.transform:transform-testing artifact for testing. Developers can use Transform to manage their composition anywhere within their app.
// With helper function
var sourceState by mutableStateOf(0)
val state = transform(initialValue = 0, scope = myCoroutineScope) {
// any time this state changes, this lambda will update
sourceState
}
// With TransformScope directly
val transformScope = TransformScope()
var sourceState by mutableStateOf(0)
val state = transformScope.launchTransform(initialValue = 0) {
// any time this state changes, this lambda will update
sourceState
}
myCoroutineScope.launch {
try {
transformScope.run()
} finally {
state.dispose()
}
}
// In test with the new transformTest API
@Test
fun testStateUpdate() = transformTest {
var sourceState by mutableStateOf(0)
val state = transform(
initialValue = 0, scope = backgroundScope, dispatcher = testDispatcher
) {
sourceState
}
assertThat(state.value).isEqualTo(0)
sourceState = 1
advance()
assertThat(state.value).isEqualTo(1)
}