Florian
10/01/2021, 9:56 AM(context as Activity).apply {}
block directly into the composable function or do I have to wrap it into one of the side effects methods? I just can't wrap my head around it.
@Composable
fun TimerScreen(
viewModel: TimerViewModel = hiltViewModel(),
) {
val uiState by viewModel.uiState.collectAsState(null)
val context = LocalContext.current
[...]
val screenBrightness = if (uiState?.timerRunning == true) 0.15f else -1f // default
(context as Activity).apply {
val attributes = window.attributes
attributes.screenBrightness = screenBrightness
window.attributes = attributes
}
ScreenContent(
uiState = uiState,
actions = viewModel,
scaffoldState = scaffoldState,
bodyScrollState = bodyScrollState,
)
}
Ravi
10/01/2021, 10:18 AMfun Context.findActivity(): Activity? {
var context = this
while (context is ContextWrapper) {
if (context is Activity) return context
context = context.baseContext
}
return null
}
try this instead of casting context as Activitymyanmarking
10/01/2021, 11:06 AMCsaba Kozák
10/01/2021, 11:56 AMDisposableEffect
, so you can restore the brightness in its onDispose
block.Florian
10/05/2021, 7:49 PMFlorian
10/05/2021, 7:49 PMFlorian
10/05/2021, 7:50 PMonDispose
seems to be a nice way to do thatFlorian
10/05/2021, 8:08 PMtimerRunning
?Florian
10/05/2021, 8:26 PMval timerRunning = uiState?.timerRunning ?: false
DisposableEffect(timerRunning) {
val screenBrightness = if (timerRunning) 0.15f else -1f // default
context.findActivity()?.setScreenBrightness(screenBrightness)
onDispose {
context.findActivity()?.setScreenBrightness(-1f)
}
}
It's okay to have the timerRunning
assignment outside the DisposableEffect
, right?Florian
10/05/2021, 8:27 PMCsaba Kozák
10/06/2021, 8:35 AMFlorian
10/06/2021, 8:39 AMCsaba Kozák
10/06/2021, 8:42 AMLaunchedEffect
launches a coroutine, so you can call suspend
functions in it. DisposableEffect
provides onDispose {}
block so you can restore the side effects when it restarts/leaves the composition.Florian
10/06/2021, 8:44 AM