跪拜 Guibai
← Back to the summary

Jetpack AppState Transform: Compose State, Flow, and Async Logic in a Single ViewModel Block

Jetpack AppState Transform: Let Compose's Reactive State Break Out of the UI Layer

A task page often doesn't just display a list from the database. It also needs to choose a data source based on network state, filter tasks according to the user's selected category, and decide whether to show completed tasks based on preferences.

The difficulty is that these inputs don't necessarily use the same state model: the database returns a Kotlin Flow, user selections are stored in Compose State, and network state determines which source should be subscribed to. The filtering logic itself is simple, but connecting these inputs requires extra code.

Jetpack AppState Transform handles exactly that part. It allows us to run a Composable code block in non-UI components like a ViewModel, inside which we can read State, collect Flow, compute a result, and finally expose a Compose State.

Starting with a simple task list, we'll gradually add filtering, online/offline switching, and search. At each step, we'll compare different approaches using the same inputs and requirements.

1. Starting with two inputs: task list and filter toggle

Assume the app already has a task model:

data class Task(
    val id: Int,
    val title: String,
    val category: String,
    val isCompleted: Boolean
)

The database continuously provides tasks via a Flow. The user's "show completed tasks" toggle is stored in Compose State:

// The following properties are in the ViewModel.
private val tasksFlow: Flow<List<Task>> = repository.observeTasks()

var showCompleted by mutableStateOf(false)
    private set

The requirement is only one: whenever the list updates or the toggle changes, recalculate the visible tasks.

Using Flow: Normalize inputs first, then combine

combine can combine multiple Flows. However, showCompleted is a Compose State, so it needs to be bridged via snapshotFlow:

val visibleTasks: StateFlow<List<Task>> = combine(
    tasksFlow,
    snapshotFlow { showCompleted }
) { tasks, show ->
    tasks.filter { show || !it.isCompleted }
}.stateIn(
    scope = viewModelScope,
    started = SharingStarted.Eagerly,
    initialValue = emptyList()
)

This code is done in three steps: snapshotFlow converts the toggle's changes into a Flow, combine re-filters whenever either input updates, and stateIn retains the latest result and provides an initial value.

Here we use Eagerly so that collection continues with the ViewModel scope, making it easier to compare with the Transform approach. In practice, you could also use WhileSubscribed to start/stop upstream based on subscription.

Using Transform: Read inputs directly during computation

For the same requirement, Transform can be written like this:

val visibleTasks: State<List<Task>> = transform(
    initialValue = emptyList(),
    scope = viewModelScope
) {
    val tasks = tasksFlow.collectAsState(initial = emptyList()).value
    val show = showCompleted

    tasks.filter { show || !it.isCompleted }
}

The filtering logic hasn't changed. What changed is how dependencies are established: instead of converting all inputs into Flows and putting them into combine's parameter list, we read them inside the transformation block.

collectAsState collects the task Flow and exposes the latest list as Compose State. When Transform runs this block, it tracks reads of the tasks State and showCompleted. When either state changes, the transformation block is scheduled to re-run, and the new return value becomes the latest value of visibleTasks.

For example, suppose the list contains task A (incomplete) and B (completed). When the toggle is off, both approaches show A; when the toggle is turned on, both show A and B. The Flow approach triggers composition via input streams, while Transform triggers recomposition via State dependencies.

Both code snippets achieve the same display goal, but the initial values and update scheduling are not step-by-step identical: combine waits for each input to emit its first value; the Transform example, if tasks haven't arrived yet, will first compute with an empty list.

2. Why can Composable code run in a ViewModel?

We often use collectAsState in the UI: collect a Flow and pass the result to Text or LazyColumn. But it depends on Compose's runtime mechanism, not on those UI components.

The Compose runtime can track reads of State and schedule code re-execution when state changes. Transform uses this mechanism to create a Composition that doesn't draw UI, a "headless Composition".

A regular UI Composition generates UI based on state; the Composition in Transform computes a value based on state. The transformation block above only returns a task list, so it doesn't create any UI elements.

From the caller's perspective, the structure of Transform is:

val result: State<Result> = transform(
    initialValue = initialResult,
    scope = viewModelScope
) { previousResult ->
    // Read state, collect data, and finally return the computed result.
    calculateResult()
}

initialValue is the result that can be read before the first computation completes; scope determines how long this transformation can run; previousResult is the previous output, which equals the initial value on first execution.

Therefore, even if a ViewModel doesn't have its own UI Composition, you can use Composable APIs like collectAsState, remember, and LaunchedEffect within this transformation block.

AppState also provides a StateStore for storing and sharing application state. Transform, which we are discussing, is responsible for converting existing inputs into derived state.

3. Use derivedStateOf when computing a value solely from existing State

Let's narrow the requirement: what if the tasks are already in Compose State and we don't need to collect a database Flow?

var tasks by mutableStateOf(emptyList<Task>())
    private set

var showCompleted by mutableStateOf(false)
    private set

val visibleTasks: State<List<Task>> = derivedStateOf {
    tasks.filter { showCompleted || !it.isCompleted }
}

Here, derivedStateOf is sufficient. It also tracks reads of Compose State in its block, but the computation is synchronous: when an input changes, the derived value is invalidated and recalculated on the next read; no initial value or coroutine scope is needed.

Transform was useful in the previous section because the tasks come from an async Flow, and the computation block needs to call collectAsState. derivedStateOf takes an ordinary Kotlin lambda and cannot call that Composable API.

Of course, you could start a coroutine externally, collect the Flow into Compose State, and then pass it to derivedStateOf. That's also doable, but the data collection and lifecycle are handled by external code.

Comparison derivedStateOf AppState Transform Flow.combine
How input dependencies are established Tracks State reads in the block Tracks State reads in a Composable block; Flow can be integrated via collectAsState Explicitly passes input Flows
How async sources are handled Convert to State externally first Call Composable APIs inside the block Organize with Flow operators
How output is obtained Computes derived value synchronously on read Updates State after Composition runs Emits combined results, can be kept via stateIn
Suitable starting point Inputs are already Compose State Inputs are mixed State and Flow, and need Compose capabilities Inputs are all Flows

If all inputs are Flows, combine is still straightforward. If all inputs are State and only synchronous computation is needed, Transform is usually not needed either. Transform's usefulness becomes more apparent with mixed inputs and conditional collection.

4. Adding network state: subscribing to different sources when online/offline

Now let's make the task page support offline mode: when online, read remote tasks; when offline, read local Room data. The filter toggle still works.

First, keep two Flows to avoid re-invoking Repository to create objects each time state is computed:

private val remoteTasksFlow = repository.observeRemoteTasks()
private val localTasksFlow = repository.observeLocalTasks()

var isOnline by mutableStateOf(true)
    private set

In a real project, isOnline could be maintained by a network monitor; here we represent it with Compose State.

Flow approach: switching collection with flatMapLatest

private val activeTasksFlow = snapshotFlow { isOnline }
    .flatMapLatest { online ->
        if (online) remoteTasksFlow else localTasksFlow
    }

val visibleTasks: StateFlow<List<Task>> = combine(
    activeTasksFlow,
    snapshotFlow { showCompleted }
) { tasks, show ->
    tasks.filter { show || !it.isCompleted }
}.stateIn(
    scope = viewModelScope,
    started = SharingStarted.Eagerly,
    initialValue = emptyList()
)

flatMapLatest expresses "when network state changes, cancel collection from the old source and collect the new one". combine continues to combine tasks and the filter toggle.

Transform approach: collecting in conditional branches

val visibleTasks: State<List<Task>> = transform(
    initialValue = emptyList(),
    scope = viewModelScope
) {
    val tasks = if (isOnline) {
        remoteTasksFlow.collectAsState(initial = emptyList()).value
    } else {
        localTasksFlow.collectAsState(initial = emptyList()).value
    }

    val show = showCompleted
    tasks.filter { show || !it.isCompleted }
}

Here we no longer build an additional activeTasksFlow. The transformation block reads isOnline, enters the current branch, and collects the corresponding data source.

When network state changes, Compose schedules the transformation block to recompose. The original branch leaves the Composition and its collection task is cancelled; the new branch enters the Composition and starts collecting the new Flow.

What makes this work is the Composition's management of collection tasks within branches. Simply writing a normal if doesn't automatically give you subscription and cancellation.

Both approaches can switch sources. The difference is: Flow connects processing steps explicitly with operators; Transform expresses the same business condition using Compose's execution branches and dependency tracking.

5. Summarizing filter conditions into a page state

Now add category selection, so the page knows both the current tasks and network state.

data class TaskUiState(
    val tasks: List<Task> = emptyList(),
    val isOnline: Boolean = true,
    val isLoading: Boolean = true
)

The following ViewModel summarizes the previous logic:

class TaskViewModel(
    repository: TaskRepository,
    private val networkMonitor: NetworkMonitor
) : ViewModel() {
    private val remoteTasksFlow = repository.observeRemoteTasks()
    private val localTasksFlow = repository.observeLocalTasks()

    var selectedCategory by mutableStateOf<String?>(null)
        private set

    var showCompleted by mutableStateOf(false)
        private set

    val uiState: State<TaskUiState> = transform(
        initialValue = TaskUiState(
            isOnline = networkMonitor.isOnline.value
        ),
        scope = viewModelScope
    ) { previous ->
        val online = networkMonitor.isOnline.value
        val category = selectedCategory
        val show = showCompleted

        val tasks = if (online) {
            remoteTasksFlow.collectAsState(initial = null).value
        } else {
            localTasksFlow.collectAsState(initial = null).value
        }

        if (tasks == null) {
            // New source hasn't provided data yet: keep the original list but update network and loading state.
            previous.copy(isOnline = online, isLoading = true)
        } else {
            TaskUiState(
                tasks = tasks.filter { task ->
                    (show || !task.isCompleted) &&
                        (category == null || task.category == category)
                },
                isOnline = online,
                isLoading = false
            )
        }
    }

    fun selectCategory(category: String?) {
        selectedCategory = category
    }

    fun setCompletedVisible(visible: Boolean) {
        showCompleted = visible
    }
}

This example assumes the Repository provides two Flow<List<Task>>s, and the network monitor provides a State<Boolean>. Imports, dependency injection, and error handling are omitted.

Now, network state, category, and display preference are all read inside the transformation block, and the task Flow is integrated via collectAsState. Changing any relevant input will recalculate the final state.

This example also uses the previous output previous. When the data source switches and the new Flow hasn't emitted a list yet, the page keeps the old tasks, shows a loading indicator, and immediately updates the online flag. When the new list arrives, it's filtered with the current category and preference.

This is a product choice: the old list temporarily shown during loading is not guaranteed to match the latest filter conditions. If you must hide old content immediately when switching categories, you can return an empty list and loading state when tasks == null.

The UI only needs to read the final result:

@Composable
fun TaskScreen(viewModel: TaskViewModel) {
    val state by viewModel.uiState

    Column {
        Text(if (state.isOnline) "Online" else "Offline")

        if (state.isLoading) {
            LinearProgressIndicator()
        }

        LazyColumn {
            items(state.tasks, key = { it.id }) { task ->
                Text(task.title)
            }
        }
    }
}

The page doesn't need to decide whether to subscribe to remote or local data, nor is it responsible for reassembling multiple inputs. Those rules are summarized in a single state in the ViewModel.

6. Search debouncing: using Compose's side-effect APIs for waiting and cancellation

Another use of Transform is using APIs like LaunchedEffect during state computation. Take task search as an example: after the user stops typing for 300 ms, trigger a search; when a new query comes, cancel the old search; and continuously receive results for the current query.

Using Flow, you can organize it like this:

val searchResults: Flow<List<Task>> = snapshotFlow { searchQuery }
    .debounce(300)
    .distinctUntilChanged()
    .flatMapLatest { query ->
        if (query.isBlank()) {
            flowOf(emptyList())
        } else {
            repository.searchTasks(query)
        }
    }

debounce waits for input to stabilize, flatMapLatest switches to the latest search flow. Here we assume searchQuery is Compose State and Repository returns Flow<List<Task>>.

Using Transform, you can let LaunchedEffect manage this asynchronous work:

val searchResults: State<List<Task>> = transform(
    initialValue = emptyList(),
    scope = viewModelScope
) {
    val query = searchQuery
    var results by remember { mutableStateOf(emptyList<Task>()) }

    LaunchedEffect(query) {
        delay(300)

        if (query.isBlank()) {
            results = emptyList()
        } else {
            repository.searchTasks(query).collect { tasks ->
                results = tasks
            }
        }
    }

    results
}

The transformation block reads searchQuery. When the query changes, recomposition is triggered. The key of LaunchedEffect(query) changes, so the old coroutine is cancelled and a new one starts waiting. If the user continues typing during the waiting period, the old search won't execute; if a search has already started, collection from the old flow is cancelled.

remember preserves intermediate results, LaunchedEffect updates it, and Transform outputs the latest result. This demonstrates Transform's extra capability over synchronous derived computations: it can organize both state and asynchronous work in a single Composition.

Both approaches retain the original result until a new result arrives; an empty query also waits 300 ms before clearing. They have the same interaction goal, but Flow and Compose use different scheduling mechanisms, so you shouldn't assume every intermediate update is exactly the same.

If only the first result is needed, you can switch to first(). Then subsequent updates won't be received; choose based on the Repository's data semantics.

7. Which data is not suitable for Transform?

A task page only needs to know "what to show now." When inputs change rapidly, you often don't need every intermediate frame shown.

Transform fits this kind of current-state computation. Suppose an input goes through A → B → C before the next recomposition; the computation may only use the latest C. If the new output equals the old output, no new state change is triggered.

But some business cases care about every occurrence:

Scenario Why you can't keep only the current state
Recording payment flows Each transition (pending, processing, success) may need to be logged
Computing sensor cumulative values or averages Two consecutive identical readings each represent a valid sample
Maintaining undo history Intermediate changes cannot be lost because the next update arrives
Sending commands, processing queue items The same command appearing twice may need to be executed twice

These scenarios should be handled by an appropriate event pipeline. For example, use Flow's scan or runningFold to compute cumulative results, then integrate that into Transform to combine with other display state.

Whether every input can be preserved also depends on upstream buffering, merging, and consumption. Simply changing a type to Flow doesn't automatically restore events that have already been dropped.

Similarly, if a producer must wait for a consumer to process current data, backpressure should be designed in the stream layer. Assigning a Compose State does not suspend to wait for a consumer.

8. Determine execution thread and lifecycle before using

The transformation may run on a background thread

Transform's dispatcher defaults to Dispatchers.Default, but you can specify it explicitly:

val state = transform(
    initialValue = TaskUiState(),
    scope = viewModelScope,
    dispatcher = Dispatchers.Default
) {
    // Read state and compute result.
    TaskUiState()
}

Therefore, the transformation is not guaranteed to run on the main thread. When filtering large collections, this can offload computation to the background, but it doesn't automatically reduce computation; high-frequency updates or complex algorithms still need real measurement.

If the transformation accesses external objects that require a specific thread, you should choose an appropriate dispatcher. Compose State can be tracked, but that doesn't mean any object in the block can safely cross threads.

While the ViewModel is alive, the transformation can keep running

With viewModelScope, Transform will keep running for the lifetime of that scope. When the page goes to background, Flow collection inside it won't automatically stop.

This differs from the following Flow strategy:

repository.observeTasks().stateIn(
    scope = viewModelScope,
    started = SharingStarted.WhileSubscribed(5000),
    initialValue = emptyList()
)

That strategy allows the upstream to stop after five seconds without subscribers. Whether it's suitable depends on whether tasks need to keep updating when no UI is observing.

If the transformation should follow the calling UI Composition, you can use the @Composable transform overload; if you need continuous state maintenance during the ViewModel's lifetime, the scoped overload in this article is appropriate.

Updates are not synchronous

derivedStateOf can compute synchronously on read. Transform, however, needs to wait for the Composition to execute. If you read the output immediately after an input change, you shouldn't assume the new result is already available.

Accordingly, testing needs to advance both coroutine scheduling and recomposition. AppState provides transformTest and TransformTestScope to control execution during testing.

9. Configuring dependencies

The following uses AppState Transform 1.0.0-alpha01 as an example to show how to configure dependencies.

Declare the runtime and testing libraries in the version catalog:

[versions]
appstate = "1.0.0-alpha01"

[libraries]
androidx-appstate-transform = { module = "androidx.appstate.transform:transform", version.ref = "appstate" }
androidx-appstate-transform-testing = { module = "androidx.appstate.transform:transform-testing", version.ref = "appstate" }

Add the dependencies to the module:

dependencies {
    implementation(libs.androidx.appstate.transform)
    testImplementation(libs.androidx.appstate.transform.testing)
}

The module also needs to enable Compose build feature and apply the Compose Compiler Gradle plugin. Even if the module contains no UI, as long as it calls these Composable APIs, that configuration is required.

The examples in this article are for explaining state organization and were not compiled or run in a complete Android project. Imports, opt-in requirements for coroutine APIs, and plugin configuration should be added according to the actual project version. The AppState version used here is alpha, so check the version notes before integrating.

10. Putting Transform in the right place

In an app with an existing clear Flow architecture, if Repository and preference layers all provide Flow, continuing to use operators like combine and flatMapLatest is often natural. There's no need to rewrite the entire chain just to introduce a new library.

When presentation state depends on Compose State, database Flow, network conditions, and asynchronous operations, Transform offers another organizing approach: read inputs, choose sources, compute output in a single block, and let Compose maintain those read relationships.

Repository still handles data access, and use cases still handle business rules. Transform can be placed in a state holder to combine these results with user choices into final page state. It can also be used in other non-UI components, but you should first clarify lifecycle and thread requirements.

From the task page in this article, Transform doesn't change filtering rules, nor does it make the database Flow disappear. It changes how states are connected: developers can use Compose's read tracking, conditional branches, and side-effect APIs to maintain a continuously updated result in a ViewModel.

For complex presentation state, this approach is worth evaluating in a small-scope feature, then decide based on testing, performance, and lifecycle behavior.