Skip to content

Callbacks called multiple times unnecessarily #635

Description

@slishak

Firstly - thanks so much for the new callback context and multi-output features added recently. They have significantly improved the development experience!

In the example app below, I'm using both of the new features. When a button is clicked, both sliders are updated from the same callback, and then the graph is updated based on the sliders. It all works fine, but on every button click the plot callback is actually triggered twice (once for each slider) even though both sliders are updated "simultaneously".

Is there a way to prevent this? In my real app, the plot callback is potentially quite heavy (represented by the time.sleep) and there are more than 2 sliders linked to it, so I'd prefer to only call it once when all of the sliders are updated by one multi-output callback.

fromtimeimportsleepimportdashfromplotlyimportgraph_objsasgoimportdash_html_componentsashtmlimportdash_core_componentsasdccfromdash.dependenciesimportOutput, Input, Statefromdash.exceptionsimportPreventUpdateapp=dash.Dash(__name__)
app.scripts.config.serve_locally=Trueapp.layout=html.Div([
html.Button('Button 1', id='b1'),
html.Button('Button 2', id='b2'),
dcc.Slider(id='slider1', min=-5, max=5),
dcc.Slider(id='slider2', min=-5, max=5),
dcc.Graph(id='graph')
])
@app.callback( [Output('slider1', 'value'),Output('slider2', 'value')], [Input('b1', 'n_clicks'),Input('b2', 'n_clicks')])defupdate_sliders(button1, button2):
ifnotdash.callback_context.triggered:
raisePreventUpdatetriggered=dash.callback_context.triggered[0]['prop_id'].split('.')[0]
iftriggered=='b1':
return-1, -1else:
return1, 1@app.callback(Output('graph', 'figure'), [Input('slider1', 'value'),Input('slider2', 'value')])defupdate_graph(s1, s2):
sleep(1)
print('Called x={}, y={}'.format(s1, s2))
scatter=go.Scatter(x=[s1], y=[s2], mode='markers')
layout=go.Layout(xaxis={'range': [-5, 5]}, yaxis={'range': [-5, 5]})
fig=go.Figure(data=[scatter], layout=layout)
returnfigif__name__=='__main__':
app.run_server(debug=True, port=6060, threaded=False)
dash==0.39.0
dash-core-components==0.44.0
dash-html-components==0.14.0
dash-renderer==0.20.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions