2

This question is inspired by this post where printouts from a called functions are displayed inside a shiny app when the code is running.

My question is basically, what is the difference between:

message('hello')
#and
sink(file=stderr())
cat('hello')

In the documentation for message it says that:

The default handler sends the message to the stderr() connection.

I haven't found a way to illustrate the difference in just R without shiny , but in this example the 2 functions behave differently

library(shiny)
library(shinyjs)

myPeriodicFunction1 <- function(){
  for(i in 1:5){
    msg <- paste(sprintf("[1] Step %d done.... \n",i))
    message(msg)
    Sys.sleep(1)
  }
}

myPeriodicFunction2 <- function(){
  for(i in 1:5){
    msg <- paste(sprintf("[2] Step %d done.... \n",i))
    cat(msg)
    Sys.sleep(1)
  }
}

runApp(shinyApp(
  ui = fluidPage(
    shinyjs::useShinyjs(),
    actionButton("btn1","Message"),
    actionButton("btn2","Sink to stderr"),
    textOutput("text")
  ),
  server = function(input,output, session) {
    observeEvent(input$btn1, {
      withCallingHandlers({
        shinyjs::text("text", "")
        myPeriodicFunction1()
      },
      message = function(m) {
        shinyjs::text(id = "text", text = m$message, add = FALSE)
      })
    })
    observeEvent(input$btn2, {
      withCallingHandlers({
        shinyjs::text("text", "")
        sink(file=stderr())
        myPeriodicFunction2()
        sink()
      },
      message = function(m) {
        shinyjs::text(id = "text", text = m$message, add = FALSE)
      })
    })
  }
))

Can anyone help me straighten this out?

Community
  • 1
  • 1
RmIu
  • 4,357
  • 1
  • 21
  • 24

0 Answers0