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 - Flow By ViewModel")
}
)},
content = { MainContent() },
backgroundColor = Color(0xFFEDEAE0)
)
}
}
}
}
@Composable
fun MainContent() {
val viewModel = viewModel<MyViewModel>()
val color = viewModel.colorsFlow.collectAsState(initial = "Red")
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 colorsFlow = flow {
val colors = listOf(
"Red","Green","Blue","Yellow","Black"
)
for (color in colors) {
emit(color)
Log.d("xapp",color)
delay(3000)
}
}
}
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 - Kotlinx serialization build json array
- jetpack compose - Kotlinx serialization build json object
- jetpack compose - Kotlinx serialization decode josn element
- jetpack compose - How to use kotlin flow
- jetpack compose - How to use ViewModel state
- jetpack compose - Count up flow by 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
- jetpack compose - ViewModel Room edit update data
- jetpack compose - ViewModel Room delete clear data
- compose glance - How to create app widget
- jetpack compose - Icon from vector resource
- jetpack compose - IconButton from vector resource