Thread
#compose
    henrikhorbovyi

    henrikhorbovyi

    2 years ago
    Hello everyone, I know it's simple. but how can I change activity with compose? Specifically inside a click block of a ListItem.
    jim

    jim

    2 years ago
    The minimal diff to fix the error is to add a line above the ListeItem that says 
    val context = ContextAmbient.current
     and then use the 
    context
     variable instead of reading from the ambient inside the onClick handler. But know that every time you read from an Ambient, I cry a little inside.  Please don't structure your code that way.  Not only are you depending on an API that makes your widget impossible to unit-test, but you're also depending on ambients for something that isn't actually ubiquitous, which is an antipattern IMO, and you're baking implicit app knowledge into your widgets. Instead, pass a handler down into whichever composable is rendering your list item, and have the lambda contain a reference to the Context which was passed down from the current Activity.  It's hard to be more specific, because I can't see the rest of your code, but basically your composable functions should ideally know nothing about Context, and just call a function handler that was passed in when a relevant event occur.  Widgets should generally accept lambdas instead of "knowing how to perform bespoke actions, like launching a specific activity".
    Colton Idle

    Colton Idle

    2 years ago
    Not only are you depending on an API that makes your widget impossible to unit-test,
    👀 This sentence just made me realize how much I still have yet to learn. 😄
    henrikhorbovyi

    henrikhorbovyi

    2 years ago
    @jim Thank you very much for your answer. I'm sure I know much more now 🙂 I'll fix my code to use a lambda so to the caller can invoke this and execute some action (change activity as I wish to do)