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:
- MainActivity: - This is the entry point of the application and sets up the main screen using Jetpack Compose.
- It defines the setContentblock which describes the UI hierarchy.
- Inside setContent, theScaffoldcomposes the app bar, main content, and background color.
- It retrieves the MyViewModelinstance usingviewModelcomposable function.
 
- MainContent: - This composable function represents the main content area of the screen.
- It collects the countUpFlowfrom theMyViewModelusingcollectAsStatewith an initial value of 1. This makes the UI reactive to changes in the flow.
- It displays the current count value (color.value) inside aTextcomposable with a font size of 40sp.
 
- MyViewModel: - This class extends ViewModeland manages the application state.
- It defines a countUpFlowwhich 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.
 
- This class extends 
- build.gradle: - This file specifies the dependencies required for the project.
- It includes the necessary androidx.lifecyclelibraries 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"
}
 
 
 
- jetpack compose - Get text from url
- jetpack compose - Kotlinx serialization alternative json names
- jetpack compose - Kotlinx serialization build json array
- jetpack compose - Flow current time
- jetpack compose - How to flow a list
- jetpack compose - How to use ViewModel state
- jetpack compose - Flow using ViewModel
- jetpack compose flow - Room add remove update
- jetpack compose flow - Room implement search
- jetpack compose - Search Room data using ViewModel
- jetpack compose - ViewModel Room add insert data