Callback ALL MATCH

Hey, I’m building an app with song samples that play on button click. Unfortunately my solution is really causing performance issues. I have a variable amount of Buttons.
On click the image inside the button should change to ‘play’/‘pause’/‘unpause’ but also should the last pressed button-image go back to ‘play’ (because its not playing anymore). To do so my only solution was over ALL, however when I have over 100 Buttons this is not efficient.

@app.callback(
    Output({'type': 'play_svg', 'index': ALL}, 'src'),
    Input({'type': 'play_sample', 'index': ALL},'n_clicks'),
    State({'type': 'play_sample', 'index': ALL}, 'name'),
    State({'type': 'play_svg', 'index': ALL}, 'src')
)
def play_sample(n, urls, svgs):
    if ctx.triggered_id==None:
        raise PreventUpdate
    else:
        index = ctx.triggered_id['index']
        if svgs[index] == mod.png_to_src('pause'):
            pygame.mixer.music.pause()
            svgs[index] = mod.png_to_src('unpause')
            return svgs
        elif svgs[index] == mod.png_to_src('unpause'):
            pygame.mixer.music.unpause()
            svgs[index] = mod.png_to_src('pause')
            return svgs
        else:    
            if not os.path.exists('samples/' + urls[index].split("/")[4].split("?")[0] + '.mp3'):
                r = requests.get(urls[index])
                with open('samples/' + urls[index].split("/")[4].split("?")[0] + '.mp3', 'wb') as f:
                    f.write(r.content)
                f.close()
            pygame.mixer.music.load('samples/' + urls[index].split("/")[4].split("?")[0] + '.mp3')
            pygame.mixer.music.play(loops=3)

            #set ALL buttons to 'play'
            svgs = [mod.png_to_src('play') for _ in svgs]
            svgs[index] = mod.png_to_src('pause')
            return svgs

Is there a way to adress a specific index like

@app.callback(
    Output({'type': 'play_svg', 'index': index_number}, 'src'),

when I store the last pressed button(index_number) in a dcc.Store
or some other workaround?
Best regards

Hi @Louis

If I understand you correctly, you would like to create callbacks dynamically? If so, that’s not possible in dash up to my knowledge. What do you mean by

Does this lead to performance issues?

Hey thanks for the reply,
yeah I have sometimes way over 100/200 buttons and the ALL loads an image to the src.

I think my issue was this line here, Im calling this function too often.

Nevermind it wasnt, but now I think over ALL is the only way.
Im trying other stuff.

1 Like

Right now, I wouldn’t know how to tackle this any other way. Problem is, that your never know, which of the buttons had been clicked beforehand. Maybe try dcm buttons which all of a icon on either side of the button instead of changing the image in your html button. Maybe this decreases the amount of data for each call.