Jetpack compose: Count up flow by ViewModel

This code demonstrates a simple counter application built with Jetpack Compose and leverages ViewModel to manage the state and data flow.

Here's a breakdown of the code:

  1. MainActivity:

    • This is the entry point of the application and sets up the main screen using Jetpack Compose.
    • It defines the setContent block which describes the UI hierarchy.
    • Inside setContent, the Scaffold composes the app bar, main content, and background color.
    • It retrieves the MyViewModel instance using viewModel composable function.
  2. MainContent:

    • This composable function represents the main content area of the screen.
    • It collects the countUpFlow from the MyViewModel using collectAsState with an initial value of 1. This makes the UI reactive to changes in the flow.
    • It displays the current count value (color.value) inside a Text composable with a font size of 40sp.
  3. MyViewModel:

    • This class extends ViewModel and manages the application state.
    • It defines a countUpFlow which is a kotlinx.coroutines flow.
    • The flow emits values from 1 to 10 with a delay of 1 second between each emission.
    • It logs information about the current emitted number for debugging purposes.
  4. build.gradle:

    • This file specifies the dependencies required for the project.
    • It includes the necessary androidx.lifecycle libraries for ViewModels and Compose integration.

Summary:

This example showcases how to manage state and data flow in a Jetpack Compose application using ViewModel. The MyViewModel generates a flow that emits numbers sequentially, and the MainContent composable observes the flow and updates the UI accordingly. This approach promotes separation of concerns and simplifies state management in a Compose application.


MainActivity.kt

package com.cfsuman.composestate

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.cfsuman.composestate.ui.theme.ComposeStateTheme


class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ComposeStateTheme {
                Scaffold(
                    topBar = { TopAppBar(
                        title = {
                            Text(text = "Compose - Count Up Flow")
                        }
                    )},
                    content = { MainContent() },
                    backgroundColor = Color(0xFFEDEAE0)
                )
            }
        }
    }
}


@Composable
fun MainContent() {
    val viewModel = viewModel<MyViewModel>()
    val color = viewModel.countUpFlow.collectAsState(initial = 1)
    Log.d("xapp","recompose")

    Box(
        Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Text(text = "${color.value}", fontSize = 40.sp)
    }
}
MyViewModel.kt

package com.cfsuman.composestate

import android.util.Log
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*

class MyViewModel:ViewModel() {
    val countUpFlow = flow {
        for(i in 1..10){
            emit(i)
            delay(1000)
            Log.d("xapp","current number: $i")
        }
    }
}
build.gradle [app]

dependencies {
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.0-alpha06"
    implementation "androidx.lifecycle:lifecycle-viewmodel-compose:2.5.0-alpha06"
}
More android jetpack compose tutorials