Created
December 4, 2021 09:59
-
-
Save takahirom/d57d848b2446b582c7f8ad1b9dfc51ec to your computer and use it in GitHub Desktop.
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
@Composable | |
fun SettingScreen( | |
settingScreenState: SettingScreenState = rememberSettingScreenState() | |
) { | |
SettingScreen( | |
scaffoldState = settingScreenState.scaffoldState, | |
isDarkModeSetting = settingScreenState.isDarkMode, | |
onDarkModeSettingChanged = { | |
settingScreenState.onDarkModeChange(it) | |
} | |
) | |
} | |
@Composable | |
fun SettingScreen( | |
isDarkModeSetting: Boolean, | |
onDarkModeSettingChanged: (Boolean) -> Unit, | |
scaffoldState: ScaffoldState | |
) { | |
Scaffold(scaffoldState = scaffoldState) { | |
MySwitch(checked = isDarkModeSetting, onCheckChanged = { | |
onDarkModeSettingChanged(it) | |
}) | |
} | |
} | |
// SettingScreenState is the state holder. | |
// SettingScreenState is now just a class that does not inherit anything. | |
// This is to preserve the state of Compose so that it is not bound to any other lifecycle. | |
class SettingScreenState( | |
// You can have other Compose States. | |
val scaffoldState: ScaffoldState, | |
// If you want to access business logic or screen state, | |
// the State holder can also depend on the ViewModel. | |
// This is not a problem because ViewModel has a longer lifetime. | |
private val settingViewModel: SettingViewModel, | |
private val coroutinesScope: CoroutineScope, | |
) { | |
// Variables, etc. can be made composable if necessary. | |
val isDarkMode: Boolean | |
@Composable get() = settingViewModel.isDarkMode.collectAsState().value | |
fun onDarkModeChange(isDarkMode: Boolean) { | |
settingViewModel.onDarkModeChange(isDarkMode) | |
coroutinesScope.launch { | |
scaffoldState.snackbarHostState.showSnackbar("Dark mode changed!", ) | |
} | |
} | |
} | |
@Composable | |
fun rememberSettingScreenState( | |
scaffoldState: ScaffoldState = rememberScaffoldState(), | |
coroutinesScope: CoroutineScope = rememberCoroutineScope(), | |
settingViewModel: SettingViewModel = viewModel(), | |
) = remember { | |
SettingScreenState( | |
coroutinesScope = coroutinesScope, | |
scaffoldState = scaffoldState, | |
settingViewModel = settingViewModel | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment