Skip to content

Instantly share code, notes, and snippets.

@wch
Created March 20, 2014 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wch/9674775 to your computer and use it in GitHub Desktop.
Save wch/9674775 to your computer and use it in GitHub Desktop.

output variables are used to send information to client to display, and in most cases, they are all that's needed for an app. In some cases, though, you need more flexibility in what the server does in response to inputs.

When you set an output variable to a value, that value is sent to the client to be displayed. In contrast, observers don't (by default) send anything to the client. Their purpose is simply to execute R code. For example, observers can be used to write to files or databases. They can also be used send custom messages to the client -- these are messages that don't fit into the normal output model.

Type: Shiny
Title: Observer demo
License: MIT
Author: Winston Chang <winston@rstudio.com>
AuthorUrl: http://www.rstudio.com/
Tags: observer
DisplayMode: Showcase
shinyServer(function(input, output, session) {
# Create a random name for the log file
logfilename <- paste0('logfile',
floor(runif(1, 1e+05, 1e+06 - 1)),
'.txt')
# This observer adds an entry to the log file every time
# input$n changes.
obs <- observe({
cat(input$n, '\n', file = logfilename, append = TRUE)
})
# When the client ends the session, suspend the observer.
# Otherwise, the observer could keep running after the client
# ends the session.
session$onSessionEnded(function() {
obs$suspend()
# Also clean up the log file for this example
unlink(logfilename)
})
output$text <- renderText({
paste0("The value of input$n is: ", input$n)
})
})
shinyUI(fluidPage(
titlePanel("Observer demo"),
fluidRow(
column(4, wellPanel(
sliderInput("n", "N:",
min = 10, max = 1000, value = 200, step = 10)
)),
column(8,
verbatimTextOutput("text"),
br(),
br(),
p("In this example, what's visible in the client isn't",
"what's interesting. The server is writing to a log",
"file each time the slider value changes.")
)
)
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment