user2657817
user2657817

Reputation: 652

Understanding Reactive in R-Shiny: Preventing Re-loading Data

For a Shiny application, in server.R, I currently load my data from an inputted file through the reactive command. As I call data1() in multiple displays in server.R (see below), is there a way to only call data1 once? If I take data1() outside the render methods, I get the following error: "Operation not allowed without an active reactive context".

data1 <- reactive({
  file1 = input$file1
  if (is.null(file1))
      return(NULL) 
  data <- getNormalizedData(file1$datapath, input$value)
  data
})
output$plotFileB <- renderPlotly({
    test.out <- data1()
    ...
})
output$mytable1 = renderDataTable({
    test.out <- data1()
    test.out
})

Upvotes: 1

Views: 436

Answers (1)

DeanAttali
DeanAttali

Reputation: 26373

The nice thing about reactivity is that if you call data1() multiple times, but the input hasn't changed, the code inside data1 isn't actually going to run multiple times. It will only run once. That's the main idea of reactive variables - they cache their value, meaning that if you call them 100 times without any of their inputs changing, they only evaluate once, and the next 99 times they just immediately return their value that they remember. So the data doesn't actually get re-loaded every time you call data1(). You can convince yourself of this by putting a print() statement inside data1 and see that it only gets printed once.

I suggest doing some readings on reactive variables and reactivity to internalize this concept. This tutorial (disclaimer: I wrote it) can be a good resource on this topic: Reactivity 101

Upvotes: 3

Related Questions