Saturday, April 9, 2022

jetpack compose - Flow using ViewModel

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"
}