Controlling specific input with the isolate() function

There may be situations when the observer or conductor wants to read the value of an expression but avoid dependency. Suppose we want to import some data or perform some calculations, but only after a button has been clicked.

Let's take a look at this example:

library(shiny) 
# Define UI for application that draws a histogram 
ui<- fluidPage( 
      # Application title 
titlePanel("Old Faithful Geyser Data"), 
      # Sidebar with a slider input for number of bins  
sidebarLayout( 
sidebarPanel( 
sliderInput("bins", 
                     "Number of bins:", 
min = 1, 
max = 50, 
value = 30) 
      ),    
      # Show a plot of the generated distribution 
mainPanel( 
actionButton("goButton","Go!"), 
plotOutput("distPlot") 
      ) 
   ) 
) 
# Define server logic required to draw a histogram 
 

In the server file, we can see that output$distPlot is dependent on input$goButton. Whenever the button is clicked, the plot gets executed. However, when we wrap input$bins in isolate(), this tells Shiny that the observer or reactive expression should not be dependent on any reactive object:

server<- function(input, output) { 
output$distPlot<- renderPlot({ 
      # generate bins based on input$bins from ui.R 
      x    <- faithful[, 2]  
     # bins<- seq(min(x), max(x), length.out = input$bins + 1) 
       # Take a dependency on input$goButton 
input$goButton 
dist<- isolate( bins <- seq(min(x), max(x), length.out = input$bins + 1)) 
hist(dist,breaks = bins, col = 'darkgray', border = 'white') 
        # draw the histogram with the specified number of bins 
     # hist(x, breaks = bins, col = 'darkgray', border = 'white') 
   }) 
} 
# Run the application  
shinyApp(ui = ui, server = server) 

The flow graph looks as follows:

In the code, we can prevent the plot being shown the first time without the click button being pressed by applying conditions to it. In isolate(), not only reactive but also reactive expressions can be included. It is also possible to include multiple statements in an isolate block.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset