I have the following code in server.R:
library(shiny)
source("helpers.R")
shinyServer(function(input, output) {
output$txtOutput1 <- renderText({
someLengthyComputation(input$txtInput)[1]
})
output$txtOutput2 <- renderText({
someLengthyComputation(input$txtInput)[2]
})
output$txtOutput3 <- renderText({
someLengthyComputation(input$txtInput)[3]
})
})
helpers.R contains the method someLengthyComputation
which returns a vector of size 3. How can I get around calling it three times every time txtInput
changes and only call it once while updating all three text output controls?
You can simply place someLengthyComputation
inside a reactive
expression:
shinyServer(function(input, output) {
someExpensiveValue <- reactive({
someLengthyComputation(input$txtInput)
})
output$txtOutput1 <- renderText({
someExpensiveValue()[1]
})
output$txtOutput2 <- renderText({
someExpensiveValue()[2]
})
output$txtOutput3 <- renderText({
someExpensiveValue()[3]
})
})
someLengthyComputation
will be triggered only when input$txtInput
changes and the first of the outputs is rendered otherwise someExpensiveValue
will return a cached value.
It is also possible, although execution strategy is a little bit different, to use a combination of reactiveValues
and observe
.
If someLengthyComputation
is really expensive you should consider adding an action button or a submit button and triggering the computations only when it is clicked, especially when you use textInput
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With