Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problem: Click callback uses outdated data #106

Closed
cwsiteplan opened this issue Jan 8, 2024 · 5 comments
Closed

Problem: Click callback uses outdated data #106

cwsiteplan opened this issue Jan 8, 2024 · 5 comments

Comments

@cwsiteplan
Copy link
Contributor

cwsiteplan commented Jan 8, 2024

Hi,

i ran into a strange issue using the marker click callback.

Pushed a sample here: master...cwsiteplan:MapCompose:bug/marker-click-callback

I'm adding a click callback to the mapState initially and inside the callback i do access data that does change over time.
But somehow the callback accesses only the initially passed object.

Interestingly, moving the code outside the child composable it starts to work fine 🤔

Probably not related to your implementation at all, but would be glad if you have an idea why.

@p-lr
Copy link
Owner

p-lr commented Jan 8, 2024

You probably need to update the callback when your state changes. Try with:

@Composable
fun MyMapComposable(modifier: Modifier = Modifier, myData: MyData, mapState: MapState) {
    LaunchedEffect(myData) {
        mapState.onMarkerClick { id, x, y ->
            Log.d("Bug", "my marker state: ${myData.someList.size}")
        }
    }

    MapUI(modifier, state = mapState)
}

@cwsiteplan
Copy link
Contributor Author

cwsiteplan commented Jan 8, 2024

yep, that works too - but i'm not quite sure why i would need to do that .

shouldn't the lambda access the updated data anyways? (data is correctly updated outside of the callback)

@p-lr
Copy link
Owner

p-lr commented Jan 8, 2024

That's because LaunchedEffect can take keys as parameters, and whenever one keys changes of value, the composable block is recomposed. By using LaunchedEffect(Unit){..}, you are actually capturing the initial value of your state.

@cwsiteplan
Copy link
Contributor Author

thanks, i thought i'm aware of the concept of LaunchedEffect but assumed that the created callback (lambda) would still access the current state - seems it also captures a snapshot of the current state -interesting.

@p-lr
Copy link
Owner

p-lr commented Jan 8, 2024

Another approach is to call a method from the view-model from the lambda, passing id, x and y values. Since the view-model has all necessary data, you can do necessary operations and state changes from there, without having to worry about updating the lambda.

@p-lr p-lr closed this as completed Jan 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants