hypebright / shinyconf2024-shiny101

Shiny 101: Modular App Blueprint workshop ✨
https://hypebright.github.io/shinyconf2024-shiny101/
MIT License
30 stars 39 forks source link

"petite r strategy" vs. modules that return values #1

Open shaenzi opened 2 months ago

shaenzi commented 2 months ago

Hi Veerle, thanks so much for teaching this course, and especially for emphasising modules! I have one quick question about the "petite r" strategy. What is the advantage compared to having the module return a value and than observe that? (and one comment: if you use readRDS(here::here("data", "soccer_scorers.rds")) instead of readRDS("../data/soccer_scorers.rds"), it'll run from anywhere in your project, and you don't have to adjust it if you run it in your console :-))

hypebright commented 2 months ago

@shaenzi good question!

There are actually (at least) 4 different strategies to share data between modules:

  1. Using "stratégie du petit r": create an app-level or global-level reactiveValues object named r, that is passed along through other modules
  2. Using the session object: since session is available in every part of the app as well, you can use it as a storage mechanism
  3. Using an R6 object: creating an R6 object that is passed along through other modules
  4. Returning values from a module: make a module return a single reactive value, multiple reactive values or even data

It's mostly a matter of preference and how explicit you want to be.

Returning values from a module is a very explicit strategy: it’s clear what will be returned. This strategy keeps modules confined and small with a single goal. But the fact that is very explicit can also be seen as a downside: you have less freedom. The petit r is less explicit. You define it only once, but it doesn't even have to contain all the values it will hold. At any point in time, you can add values to it. But being less explicit can be seen as a downside: if you don't pay attention your r object will be a mess 🙃.

Personally, I like the petit r approach because I can very easily use it as a place to keep track of all kinds of states, with minimal effort. For me, it also feels the most natural. If you want to make it a bit more explicit you can force yourself to initialise all the values it will hold- but this is something that you need to do and think about.

And thanks for the note about here- you're right! Didn't put much thought into it 😬

shaenzi commented 2 months ago

Thanks for your reply! I was taught the return values approach, and often I quite like it when stuff is explicit, but it is good to know different approaches.

PS also excellent choice of topic - I spent half the weekend watching women's ⚽