The observe() function

From the functions covered in this chapter, observe() is definitely the most difficult to understand. Going deeper into the preceding definition, observe() generates outputs from reactive values (inputs) that are not rendered in an application and cannot be used inside another reactive context (for example, renderPlot() or reactive()). As a consequence of this, this function will be rather used to generate a backend process that depends on reactive values.

observe() can be used, for example, to download data depending on reactive values on the server side, such as keeping track of the application's use in a text file, similar to a log. Another very common use of observe() is to update the arguments of an input widget based on reactive values. This will be covered in the last section of this chapter.

In the following example, the application keeps track of the numbers passed as input by saving them in a log. Inside observe(), the passed values (given that it is not NA) are stored in the values log.txt file. There is no need to create the file before calling the application, as it will automatically create it if it is not found by the application. Otherwise, as the append argument is set to T, the new values will be always appended to the file. The following is the code for server.R:

library(shiny)

#initialization of server.R
shinyServer(function(input, output) {

  #Plot generation
  output$plot <- renderPlot({
    plot(1/1:input$number)
  })
  
  observe({
    if(!is.na(input$number)){
    sink("values log.txt", append=T)
    cat(input$number)
    cat("
")
    sink()}
  })

})
..................Content has been hidden....................

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