Artie Ladie
Artie Ladie

Reputation: 521

Save output to file after R shiny terminates

I have function that launches R shiny app, allowing users to select various colors.

But what if user changes their mind and deselects a color.

Hence I wish to save user output to file after R shiny terminates.

However, each time shiny is launched, the file resets so it can take in new information.

Tried session$onSessionEnded, but it gives error upon execution

Listening on http://127.0.0.1:7431
Warning: Error in .getReactiveEnvironment()$currentContext: Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
  42: stop
  41: .getReactiveEnvironment()$currentContext
  40: .dependents$register
  39: outuputdata
  37: callback [c:\RanglaPunjab/R/RanglaPunjab.R#237]

Below is code and sample input. This is entire R script

CherryPickPalette <- function (name, name2=NULL, name3=NULL){

  if ((nargs() < 2) || (nargs() > 3)){
    stop("Enter 2 or 3 valid palettes. Run ListPalette() for list of palettes.")
  }
  if (nargs() == 2){
    new_pal <- MergePalette(name,name2)
  }
  else if (nargs() == 3){
    new_pal <- MergePalette(name,name2,name3)
  }

  if (interactive()){
    colorfile <- paste(getwd(),"colorfile.txt",sep="/")
    if (!file.exists(colorfile)){
      file.create(colorfile)
    }
    shinyApp(
      ui = fluidPage(
        titlePanel("Cherry Pick Your Own Palette!"),
        sidebarPanel (hr(),
                      selectInput('col', 'Options', new_pal, multiple=TRUE, selectize=FALSE, size = 15)
                      ),
        mainPanel(
          h5('Your custom colors',style = "font-weight: bold;"),
          fluidRow(column(12,verbatimTextOutput("col"))))
      ),
      server = function(input,output,session){
        outuputdata<-  reactive({
          input$col
        })

        output$col <- { 
          renderPrint(outuputdata())
        }
        session$onSessionEnded(function(){
          message <- paste(outuputdata(),"\n")
          cat(message,file=colorfile, append=TRUE)
        })
      }

    )
  }
}

CherryPickPalette("BiryaniRice","Kulfi","Haveli2")

Upvotes: 3

Views: 746

Answers (1)

Carlos Santillan
Carlos Santillan

Reputation: 1087

You have to use isolate to access reactive values outside of a reactive context. The following worked for me

    session$onSessionEnded(function(){
      message <- paste(isolate(outuputdata()),"\n")
      cat(message,file=colorfile, append=TRUE)
    })

Upvotes: 3

Related Questions