0

I have the following shiny apps

server <- function(input, output, session) {
  rv <- reactiveValues(i = 0)

  output$myplot <- renderPlotly({
    dt = data.frame(x = 1:10, y = rep(rv$i,10))
    plot_ly(dt, x = ~x, y =~y) 
  })

  observeEvent(input$run,{
    rv$i <- 0
    observe({
      isolate({rv$i = rv$i + 1})
      if (rv$i < 10){invalidateLater(1000, session)}
    })
  })
}

ui <- fluidPage(
  actionButton("run", "START"),
  plotlyOutput("myplot")
)

shinyApp(ui = ui, server = server)

The action button works fine once: if I click on it, the plot gets updated. But the problem is I can't click on it twice as it makes the app crash.

I would like that, each time I click on the action button, the values of rv$i get back to 0 and the animation restarts all over again.

K.Hua
  • 769
  • 4
  • 20

1 Answers1

1

It is not a good idea to put an observer inside another observer. Just put the inner observer outside and it will work.

library(shiny)
library(plotly)

server <- function(input, output, session) {
  rv <- reactiveValues(i = 0)

  output$myplot <- renderPlotly({
    dt = data.frame(x = 1:10, y = rep(rv$i,10))
    plot_ly(dt, x = ~x, y =~y, mode = "markers", type = 'scatter') 
  })

  observeEvent(input$run,{
    rv$i <- 0
  })

  observe({
    isolate({rv$i = rv$i + 1})
    if (rv$i < 10){invalidateLater(1000, session)}
  })

}

ui <- fluidPage(
  actionButton("run", "START"),
  plotlyOutput("myplot")
)

shinyApp(ui = ui, server = server)
Geovany
  • 5,389
  • 21
  • 37