State not updating properly?

For some reason, a state variable does not seem to be updating as expected, even within the same execution instance of the app. Here's the code:

def eventHandler(evt) {
    state.variable[id] = evt.getValue()
    log.debug "Value of state variable is ${state.variable[id]}"
    methodCall(id)
}

def methodCall(id) {
    log.debug "Value of state variable is ${state.variable[id]}"
}

Is there any apparent reason why state.variable[id] would have a different value in methodCall(id) than when it was set in the eventHandler? The log shows the value in methodCall is the value BEFORE it was set in the eventHandler. I assume the methodCall makes it to where this is the SAME execution instance of the app, and not a situation where a different instance is trying to access a state variable that another instance has not yet written out, right?

What is setting id? Could it have changed somehow? And where is id declared? Are you sure multiple events didn’t fire at the same time? Could you show the logs that illustrate the problem?

My gut says you gave us pseudo code. Does the code you posted reproduce the problem? If not can you show the actual code? My guess is the error is actually elsewhere.

1 Like

What is firing the event handler? If there are multiple events with different event values writing and reading to the same id, you may have a concurrency issue (race condition).

Edit: @dman2306 beat me to it.

1 Like

Yeah, you're right. It was a bug elsewhere. I recalled seeing a post somewhere on the forums about state not "taking" so I assumed it could be related. But doesn't look like it is this time. Thanks for pointing me in the right direction.

1 Like