Skip to content

Instantly share code, notes, and snippets.

@pepijntb
Created April 22, 2023 11:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pepijntb/44bb8e29912b7eb180dca180a125a8e7 to your computer and use it in GitHub Desktop.
Save pepijntb/44bb8e29912b7eb180dca180a125a8e7 to your computer and use it in GitHub Desktop.
This looks reasonable to me but it doens't work
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlin.time.Duration.Companion.seconds
class MainActivity : ComponentActivity() {
private val viewModel: MainViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navController = rememberNavController()
val state by viewModel.state.collectAsState()
NavHost(navController = navController, startDestination = "screen1") {
screen1 {
navController.navigate("screen2")
viewModel.startCounting()
}
screen2(state)
}
}
}
}
class MainViewModel : ViewModel() {
private val _state = MutableStateFlow(1)
val state = _state.asStateFlow()
fun startCounting() {
viewModelScope.launch {
repeat(10) {
_state.update { it + 1 }
delay(1.seconds)
}
}
}
}
fun NavGraphBuilder.screen1(
onStartCounting: () -> Unit,
) {
composable("screen1") {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(text = "Screen 1")
Spacer(modifier = Modifier.height(16.dp))
Button(onClick = onStartCounting) {
Text(text = "Click")
}
}
}
}
fun NavGraphBuilder.screen2(
state: Int,
) {
composable("screen2") {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(text = "Count: $state")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment