Can R Shiny display different views for two simultaneous users, interacting with one another?

后端 未结 1 466
独厮守ぢ
独厮守ぢ 2021-01-06 14:51

Typically a Shiny server would spawn separate instances for individual users, so that multiple people can individually use the same app at the same time. This answer shows h

相关标签:
1条回答
  • 2021-01-06 15:26

    I had the same challenge a couples of years ago when i implemented "Risk" (the board game) as a shiny app.

    A quick outline how i approached it back then:

    If you use the session parameter in the server function, you can create a local/secret reactiveValue() within that session / for that user and you can set reactiveValues() outside the server function for "global infos" that are accessible across sessions.

    The latter approach is probably the more surprising one as we are usually "forced" to define reactive behaviour within the server function. But it works, see the example below.

    Reproducible example:

    library(shiny)
    
    ui <- fluidPage({
      uiOutput("moreControls")
    })
    
    global <- reactiveValues(info  = "public info: I can be seen by everyone", amountUser = 0, userIdToPlay = 1)
    
    server <- function(input, output, session) {
      local <- reactiveValues(secret = paste0("My secret number is ", sample(6, 1)))
    
      observe({
        isolate(global$amountUser <-  global$amountUser + 1)
        isolate(local$userId <- global$amountUser)
      })
    
      observeEvent(input$finish,{
        global$userIdToPlay <- 3 - global$userIdToPlay # assumes two players (for MVE)
      })
    
      output$moreControls <- renderUI({
        global$userIdToPlay
        isolate({
          if(local$userId == global$userIdToPlay){
            return(
              tagList(
                h2("my time to play"),
                selectInput("a", "b", letters),
                actionButton("finish", "finish")
              )
            )
          }else{
            return(
              h2("not my time to play")
            )
          }
        })
      })
    
    }
    shinyApp(ui, server)
    
    0 讨论(0)
提交回复
热议问题