Using R6 objects to share objects between sessions via the global.R

99 views
Skip to first unread message

Nick Jhirad

unread,
May 22, 2016, 1:20:59 AM5/22/16
to Shiny - Web Framework for R
So, I was playing around with R6 classes in shiny, and realized that I could use them to pass info between shiny sessions on the same app

I'm curious though:

How reliable/safe is this? where is the object actually stored? is there a risk that these shared objects (on say, shinyapps.io) could be used by user to store large amounts of arbitrary stuff on the server?

Example:

The idea is, if we have a shared object, that each server is an instance of, they can all effect a shared repository of data, so instead of doing all our coding in the server.R file, we do it in the global.R

The neat thing is, this allows people to actually communicate with one another between shiny sessions on the same app.

Example:

global.R

library(R6)
library(shiny)

# Create a Server Object that has a method 'run' that is called by the server
# file. This allows the method to have access to internal objects, thus, each
# each instance of a shiny application can access the same shared objects as
# every other instance of that run function (since they all can effect the
# same class object

server <- R6Class(
  classname = 'server',
  public = list(
  # sharedObject is what we will pass between sessions.
  sharedObject = list(),
  initialize = function() {
  },
  run = function(input, output, session) {
    output$CalcOutput <- renderText({
     self$sharedObject <- input$number
     input$number
   })
   output$CalcOutput2 <- renderText({
     input$Friends
     self$output
   })
  }
 )
)

# Create the object, everyone shares this.
channel <- server$new()

ui.R

 library(shiny)
 fluidPage(
   numericInput('number','Number',100000000),
   textOutput('CalcOutput'),
   actionButton('Friends','Whats My Friends Num?'),
   textOutput('CalcOutput2')
 )

server.R

# Now, each instance will be 
channel$run

Load up 2 copies of the app (either on your server, or through a browser)

change the number on one of the two apps, and then press the button to check it on the other app, you'll find that it's changed.

Nick Jhirad

unread,
May 23, 2016, 5:33:49 PM5/23/16
to Shiny - Web Framework for R
Hmm, this worked... but now I can't seem to reproduce... Really confused

Nick Jhirad

unread,
May 23, 2016, 5:41:30 PM5/23/16
to Shiny - Web Framework for R
Got it to work again, I just need to call:

`assign('channel', server$new(),envir = .GlobalEnv)` instead of `channel <- server$new()`

I guess that explains where it's being stored... 
Reply all
Reply to author
Forward
0 new messages