Skip to content

Instantly share code, notes, and snippets.

@vyachin
Created November 26, 2024 19:46
Show Gist options
  • Save vyachin/0051beda7be81ddbee3abe7b86b4fee8 to your computer and use it in GitHub Desktop.
Save vyachin/0051beda7be81ddbee3abe7b86b4fee8 to your computer and use it in GitHub Desktop.
Jetpack compose condition navigation
package com.example.myapplication
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.myapplication.ui.theme.MyApplicationTheme
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
val isAuthStatFlow = MutableStateFlow(false)
val isAuth = isAuthStatFlow.asStateFlow().collectAsStateWithLifecycle()
MyApplicationTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
if (isAuth.value) {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "main") {
composable("main", content = {
Column {
Button(onClick = { isAuthStatFlow.value = false }) {
Text("logout")
}
Button(onClick = { navController.navigate("profile") }) {
Text("profile")
}
}
})
composable("profile", content = {
Button(onClick = { navController.popBackStack() }) {
Text("back from profile")
}
})
}
} else {
Column(modifier = Modifier
.fillMaxSize()
.padding(innerPadding)) {
Button(onClick = { isAuthStatFlow.value = true }) {
Text("login")
}
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment