Created
November 29, 2024 15:55
-
-
Save vyachin/d8857ff8017b4225ef7415682764aec5 to your computer and use it in GitHub Desktop.
Jetpack compose navigation with login screen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.material3.Button | |
import androidx.compose.material3.Text | |
import androidx.compose.runtime.LaunchedEffect | |
import androidx.compose.ui.Modifier | |
import androidx.lifecycle.compose.collectAsStateWithLifecycle | |
import androidx.lifecycle.lifecycleScope | |
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.Dispatchers | |
import kotlinx.coroutines.flow.MutableStateFlow | |
import kotlinx.coroutines.launch | |
class MainActivity : ComponentActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
enableEdgeToEdge() | |
val isAuth = MutableStateFlow(false) | |
setContent { | |
val _isAuth = isAuth.collectAsStateWithLifecycle() | |
val navController = rememberNavController() | |
val startDestination = if (_isAuth.value) "home" else "login" | |
MyApplicationTheme { | |
NavHost(navController = navController, startDestination = startDestination) { | |
composable("login") { | |
Button(onClick = { isAuth.value = true }) { | |
Text("Login") | |
} | |
} | |
composable("home") { | |
Column(modifier = Modifier.fillMaxSize()) { | |
Button(onClick = { isAuth.value = false }) { | |
Text("Logout") | |
} | |
Button(onClick = { | |
navController.navigate("profile") | |
}) { | |
Text("profile") | |
} | |
} | |
} | |
composable("profile") { | |
Button(onClick = { navController.navigateUp() }) { | |
Text("back") | |
} | |
} | |
} | |
} | |
LaunchedEffect(this@MainActivity) { | |
lifecycleScope.launch(Dispatchers.Main) { | |
isAuth.collect { isLoggedInState -> | |
if (!isLoggedInState) { | |
navController.navigate("login") { | |
popUpTo(0) | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment