What's the reason this works: ```val context = Con...
# compose
b
What's the reason this works:
Copy code
val context = ContextAmbient.current
Card(modifier = Modifier.padding(8.dp) + Modifier.fillMaxWidth()) {
        Button(onClick = {
            Log.d(TAG, "Test")
            Toast.makeText(context, "Toast me bro", Toast.LENGTH_SHORT)
                .show()
        }) {
            Text(text = "Test")
        }
    }
}
but this doesn't
Copy code
Card(modifier = Modifier.padding(8.dp) + Modifier.fillMaxWidth()) {
        Button(onClick = {
            Log.d(TAG, "Test")
            Toast.makeText(ContextAmbient.current, "Toast me bro", Toast.LENGTH_SHORT)
                .show()
        }) {
            Text(text = "Test")
        }
    }
}
a
Think of ambients as being kind of like a
ThreadLocal
, but local to your current point in the composition instead.
onClick
doesn't run until long after the composition has finished, when the user actually clicks the button. Trying to read
ContextAmbient.current
then is kind of like having a background thread try to read a
ThreadLocal
that was set on the main thread; they're in scopes that you can't reach across.
b
Gotchya, that makes sense. Thanks for the answer!
👍 1