Skip to content

Commit 6b9ae36

Browse files
committed
add shiny streaming example; improve a couple others
1 parent d9662a6 commit 6b9ae36

File tree

1 file changed

+60
-0
lines changed
  • inst/examples/shiny/stream

1 file changed

+60
-0
lines changed

inst/examples/shiny/stream/app.R

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
library(shiny)
2+
library(plotly)
3+
4+
ui <- fluidPage(
5+
actionButton("stream", "Turn stream on/off"),
6+
plotlyOutput("plot")
7+
)
8+
9+
server <- function(input, output, session) {
10+
11+
# initial values
12+
yint <- c(0, 1)
13+
14+
# initiate graph with initial values
15+
output$plot <- renderPlotly({
16+
plot_ly(y = yint, x = seq_along(yint)) %>%
17+
add_lines()
18+
})
19+
20+
# reactiveValues() act very much like input values, but may be used to
21+
# maintain state (e.g., are we currently streaming?)
22+
rv <- reactiveValues(
23+
stream = FALSE,
24+
yend = sum(yint),
25+
n = length(yint)
26+
)
27+
28+
# turn streaming on/off when the button is pressed
29+
observeEvent(input$stream, {
30+
rv$stream <- if (rv$stream) FALSE else TRUE
31+
})
32+
33+
observe({
34+
# if we're not streaming, don't do anything
35+
if (!rv$stream) return()
36+
37+
# re-execute this code block to every 100 milliseconds
38+
invalidateLater(100, session)
39+
# changing a reactive value "invalidates" it, so isolate() is needed
40+
# to avoid recursion
41+
isolate({
42+
rv$n <- rv$n + 1
43+
rv$yend <- rv$yend + sample(c(-1, 1), 1)
44+
})
45+
46+
# add the new value to the plot
47+
plotlyProxy("plot", session) %>%
48+
plotlyProxyInvoke(
49+
"extendTraces",
50+
list(
51+
y = list(list(rv$yend)),
52+
x = list(list(rv$n))
53+
),
54+
list(0)
55+
)
56+
})
57+
58+
}
59+
60+
shinyApp(ui, server)

0 commit comments

Comments
 (0)