Can I put this `(context as Activity).apply {}` bl...
# compose
f
Can I put this
(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.
Copy code
@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,
    )
}
r
Copy code
fun 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 Activity
m
yes.casting won’t work
c
Yes, you should definitely use a side effect here. I suggest
DisposableEffect
, so you can restore the brightness in its
onDispose
block.
☝️ 1
☝🏻 1
f
@myanmarking Why does casting not work? It worked for me
@Csaba Kozák Thank you for clarification!
I was wondering where I could reset the brightness and
onDispose
seems to be a nice way to do that
But what's the key of the DisposableEffect?
timerRunning
?
Does this look correct to you @Csaba Kozák?
Copy code
val 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?
And the point of the side effect is that we don't execute this many times unnecessarily? Is that correct?
c
Your code seems to be okay. There are multiple aspects of side effects in Compose, you should read the article, i think it explains better than i would in a slack message.
f
Thank you. Yea I've read that article multiple times already, it's just not easy to understand 😅
c
You should always use a side effect when you manipulating state outside of composables. There are different kind of side effects for different use cases. Some side effects can have keys, so they only restarted when the key changes.
LaunchedEffect
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.
f
thank you for clarification!