Reactive object bindings in a non-shiny context

前端 未结 5 899
轮回少年
轮回少年 2021-02-02 12:25

Actual question

How could you either approximate the reactive environment/behavior established by shiny functions or possibly even use these very functions in a

5条回答
  •  暖寄归人
    2021-02-02 13:19

    There is a collection of test_that unit tests in location /usr/local/lib/R/site-library/shiny/tests/. They give you a good idea of how the functions/wrappers:

    • reactiveValues
    • reactive
    • observe
    • isolate

    can be used outside of a shinyServer call.

    The key is to use flushReact to make the reactivity fire off. Here, for example, is one of the tests in file test-reactivity.r, and I think it already gives you a good sense of what you need to do:

    test_that("overreactivity2", {
      # ----------------------------------------------
      # Test 1
      # B depends on A, and observer depends on A and B. The observer uses A and
      # B, in that order.
    
      # This is to store the value from observe()
      observed_value1 <- NA
      observed_value2 <- NA
    
      values <- reactiveValues(A=1)
      funcB  <- reactive({
        values$A + 5 
      })  
      obsC <- observe({
        observed_value1 <<-  funcB() * values$A
      })  
      obsD <- observe({
        observed_value2 <<-  funcB() * values$A
      })  
    
      flushReact()
      expect_equal(observed_value1, 6)   # Should be 1 * (1 + 5) = 6
      expect_equal(observed_value2, 6)   # Should be 1 * (1 + 5) = 6
      expect_equal(execCount(funcB), 1)
      expect_equal(execCount(obsC), 1)
      expect_equal(execCount(obsD), 1)
    
      values$A <- 2
      flushReact()
      expect_equal(observed_value1, 14)  # Should be 2 * (2 + 5) = 14
      expect_equal(observed_value2, 14)  # Should be 2 * (2 + 5) = 14
      expect_equal(execCount(funcB), 2)
      expect_equal(execCount(obsC), 2)
      expect_equal(execCount(obsD), 2)
    })
    

提交回复
热议问题