CapaNif
CapaNif

Reputation: 83

Avoid multiple function calls in server shiny

I have the following code in server function of a shiny app.

To plot each type of chart I need to call the getPlotData() function each time. Is there any way I can avoid it to make the app faster?

function

 #This gets Sales data for selected client data
  getPlotData <- reactive({

    inpParam <<- input$noc 
    getSalesData(inpParam)
    End_date <<- input$endDate    

    SalesClientData <<- GetSalesClientData()
    WeeklySales <<- GetWeeklyData()
    FortNightData <<- GetFortNightlyData()
    EWS <<- GetEWSData()
    MONTHLYSALES <<- GetMonthlyData()
    wtSafetyRatio <<- round(as.numeric(crossprod(MONTHLYSALES$SafetyRatio,MONTHLYSALES$Weights)/sum(MONTHLYSALES$Weights)),2)
    wtHealthScore <<- round(as.numeric(crossprod(MONTHLYSALES$HealthScore,MONTHLYSALES$Weights)/sum(MONTHLYSALES$Weights)),2)
    wtPaymentScore <<- round(as.numeric(crossprod(MONTHLYSALES$PaymentScore,MONTHLYSALES$Weights)/sum(MONTHLYSALES$Weights)),2)
    ROLLDATA <<- GetRollingData()
    EARLY_TOPUP <<- GetEarlyTopUp()

  })

  #DPD Plots
  output$DPDPLot<-renderPlotly({

    getPlotData()

    plot_ly(data=SalesClientData, x = ~Date, y = ~DPD, name='DPD', type='scatter', mode = 'lines') %>%
      add_trace(y = ~CHECKNACHDPD, name = 'CHEQUE-NACH Payment', type='bar') %>% 
      add_trace(y = ~CHKNACHBounceDPD, name = 'CHEQUE-NACH Bounce', type='bar') %>% 
      layout(title= "DPD Pattern", legend = list(orientation = "h"))

  })

  #Sales Plot
  output$SalesPlot<-renderPlotly({

    getPlotData()

    SalesDayWise = group_by(SalesClientData,Day)
    SalesDayWise = summarize(SalesDayWise,TotalSales = sum(TotalPayRecvdAdj, na.rm=TRUE))

    plot_ly(data=SalesDayWise, x = ~Day, y = ~TotalSales, name='Total Sales', type='bar') %>%
      layout(title="Daywise Sales", legend = list(orientation = "h"))

  })

Upvotes: 1

Views: 192

Answers (1)

Stupid_Intern
Stupid_Intern

Reputation: 3460

I think you are under wrong impression that just because you are calling the function again it is computing each time it is called. But in reality it is only computing once when the input widgets in the reactive expression is changed.

You can test this by putting a print statement in the function GetSalesClientData() or any other function in that reactive expression.

Even though you call the reactive expression 100 times it will compute and get new results only if the input widgets inlcuded in the reactive expression changes.

In this case it is input$noc and input$endDate

Upvotes: 1

Related Questions