Wednesday, April 6, 2022

jetpack compose - How to use kotlin flow

MainActivity.kt

package com.cfsuman.composestate

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.cfsuman.composestate.ui.theme.ComposeStateTheme
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlin.random.Random


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


@Composable
fun MainContent() {
    val colorFlow = flow<Color> {
        val color = Color(
            Random.nextInt(256),
            Random.nextInt(256),
            Random.nextInt(256)
        )
        delay(1000)
        emit(color)
    }

    val color by colorFlow.collectAsState(initial = Color.Yellow)
    Box(
        Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Box(
            Modifier
                .size(250.dp)
                .clip(CircleShape)
                .background(color)
        )
    }
}