Stop reactions with isolate()
Isolation: avoiding dependency
Sometimes it’s useful for an observer/endpoint to access a reactive value or expression, but not to take a dependency on it. For example, if the observer performs a long calculation or downloads large data set, you might want it to execute only when a button is clicked.
For this, we’ll use
actionButton. We’ll define a UI that lets the user choose number of observations to generate from the normal distribution, and has an
actionButton labeled “Go!”. You can see it in action here.
server function, there are two items to note. First,
output$distPlot will take a dependency on
input$goButton, simply by accessing it. When the button is clicked, the value of
input$goButton increases, and so
The second is that the access to
input$obs is wrapped with
isolate(). This function takes an R expression, and it tells Shiny that the calling observer or reactive expression should not take a dependency on any reactive objects inside the expression.
The resulting graph looks like this:
And here’s a walkthrough of the process when
input$obs is set to 1000, and then the Go button is clicked:
actionButton example, you might want to prevent it from returning a plot the first time, before the button has been clicked. Since the starting value of an
actionButton is zero, this can be accomplished with the following:
Reactive values are not the only things that can be isolated; reactive expressions can also be put inside an
isolate(). Building off the Fibonacci example from above, this would calculate the _n_th value only when the button is clicked:
It’s also possible to put multiple lines of code in
isolate(). For example here are some blocks of code that have equivalent effect:
In all of these cases, the calling function won’t take a reactive dependency on either of the
We love it when R users help each other, but RStudio does not monitor or answer the comments in this thread. If you'd like to get specific help, we recommend the RStudio Community as well as the Shiny Discussion Forum for in depth discussion of Shiny related questions and How to get help article for a list of the best ways to get help with R code.comments powered by Disqus