Thursday, April 7, 2022

jetpack compose - flowOf flow builder

MainActivity.kt

package com.cfsuman.composestate

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.sp
import com.cfsuman.composestate.ui.theme.ComposeStateTheme
import kotlinx.coroutines.flow.flowOf


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


@Composable
fun MainContent() {
    val colorFlow = flowOf("Red","Green","Yellow","Black")

    val color by colorFlow
        .collectAsState(initial = "Red")

    Box(
        Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Text(text = color, fontSize = 40.sp)
    }
}