Roman Woodward
Roman Woodward

Reputation: 11

R: Shiny - observeEvent invalidates too often

I am building a shiny web app, and am running into an issue when using the observeEvent function. I use it to observe changes to a few UI elements, which are then used as arguments to a function that uses renderPlot.

The problem is, when one of the UI elements is changed, it calls the function twice. Once with the original value before the alteration, and again with the new value. This is causing problems that I won't describe in detail, but I want to modify whatever is necessary so that it only calls the function once, with the new value. Does anybody know why observeEvent behaves like this or how I might get around it? Thanks

Edit: Here is the suspect code

from server:

    observeEvent(c(input$single_expNum, input$trait_exp, 
       input$plotExp_by, input$single_expDayRange), {
          output$single_expGraph <- plotExperiment(dataset, 
            input$single_expNum, input$trait_exp, 
            input$plotExp_by, input$single_expDayRange)
       }
    )

Upvotes: 1

Views: 460

Answers (2)

Jan
Jan

Reputation: 5254

In general, I agree with @divibisan that the direct use of renderPlot should work nicely. In addition, I think it's safe to say that renderPlot is the pattern recommended by Shiny. If your reactive expression (whichever you may ultimately choose) gives you trouble because of frequent updates you can slow it down with debounce or throttle.

Debouncing means that invalidation is held off for millis milliseconds. The reactive expression will only be validated until that time window has passed without a subsequent invalidation which may have an effect like this: ooo-oo-oo---- => -----------o-

Throttling, on the other hand, will not reset the time window with each invalidation. A throttled reactive "will invalidate regularly, at a rate equal to or slower than than the time window" (from the manual): ooo-oo-oo---- => o--o--o--o---

Upvotes: 0

divibisan
divibisan

Reputation: 12155

It's hard for me to say exactly why this is happening, but shiny often does wonky things when your expressions are over-complicated or designed in a way that is different than the designers of shiny intended. This is how I would rewrite your code example to make it more in line with shiny doctrine. I wouldn't be surprised if that fixed your problem:

output$single_expGraph <- renderPlot({
    # I assume here that plotExperiment() is a function that returns a plot
    plotExperiment(dataset,
                   input$single_expNum, input$trait_exp,
                   input$plotExp_by, input$single_expDayRange)
})

Upvotes: 1

Related Questions