Is there any way to set priority in reactive functions in Shiny?

Viewed 266

I have a problem with 2 reactive functions. The thing is, I need one of them to execute before the second one. Here is the code:

    sumItemsValues <- reactive({
      actualData <- switch (input$sumTabs,
                            area = sumAreaValues(),
                            kg = sumKgValues(),
                            yield = sumYieldValues(),
                            profits = sumProfitsValues(),
                            price = sumPriceValues(),
                            profitability = sumProfitabilityValues()
      )
    })
    
    sumValues <- reactive({
        actualData <- switch (input$sumTabs,
                            area = areaSum(),
                            kg = kgSum(),
                            yield = yieldSum(),
                            profits = profitsSum(),
                            price = priceSum(),
                            profitability = profitabilitySum()
        )
    })

Between this 2 functions, there are more functions, and when I run the app and switch across the tabs for a short period of time I see an error, but it disappears fastly. The error is because It tries to execute first the second function, and the second function requires that first function is executed. Thanks for yout time.

2 Answers

You could use req in the second function :

 sumItemsValues <- reactive({
      switch (input$sumTabs,
              area = sumAreaValues(),
              kg = sumKgValues(),
              yield = sumYieldValues(),
              profits = sumProfitsValues(),
              price = sumPriceValues(),
              profitability = sumProfitabilityValues()
      )
    })
    
    sumValues <- reactive({
        req(sumItemsValues())
        switch (input$sumTabs,
                area = areaSum(),
                kg = kgSum(),
                yield = yieldSum(),
                profits = profitsSum(),
                price = priceSum(),
                profitability = profitabilitySum()
        )
    })

Instead of using reactive conductors (reactive), you can use reactive values and observeEvent, which has a priority option:

sumItemsValues <- reactiveVal(NULL)
sumValues <- reactiveVal(NULL)

observeEvent(input$sumTabs, {
  actualData <- switch(
    input$sumTabs,
    area = sumAreaValues(),
    kg = sumKgValues(),
    yield = sumYieldValues(),
    profits = sumProfitsValues(),
    price = sumPriceValues(),
    profitability = sumProfitabilityValues()
  )
  sumItemsValues(actualData)
}, priority = 2)

observeEvent(input$sumTabs, {
  actualData <- switch(
    input$sumTabs,
    area = areaSum(),
    kg = kgSum(),
    yield = yieldSum(),
    profits = profitsSum(),
    price = priceSum(),
    profitability = profitabilitySum()
  )
  sumValues(actualData)
}, priority = 1)
Related