Agenda
Reactive calculations
Your turn
Overriding reactivity
Side effects
Important
@reactive.calc
creates calculations whose results can be used by one or more outputs @output
@render.table
def df():
rand = np.random.rand(input.n_rows(), 1)
df = pd.DataFrame(rand, columns=["col_1"])
return df
@output
@render.plot
def hist():
rand = np.random.rand(input.n_rows(), 1)
df = pd.DataFrame(rand, columns=["col_1"])
plot = (
ggplot(df, aes(x="col_1"))
+ geom_histogram(binwidth=0.1, fill="blue", color="black")
+ labs(x="Random Values", y="Frequency", title="Histogram of Random Data")
)
return plot
Warning
@reactive.calc
def sampled_df():
rand = np.random.rand(input.n_rows(), 1)
df = pd.DataFrame(rand, columns=["col_1"])
@render.table
def df():
return sampled_df()
@render.plot
def hist():
return (
ggplot(sampled_df(), aes(x="col_1"))
+ geom_histogram(binwidth=0.1, fill="blue", color="black")
+ labs(x="Random Values", y="Frequency", title="Histogram of Random Data")
)
@reactive.calc
decoratorAgenda
Reactive calculations
Your turn
Overriding reactivity
Side effects
Agenda
Reactive calculations
Your turn
Overriding reactivity
Side effects
Tip
This isn’t always the user interaction you want:
Important
@reactive.event
to explicitly specify the trigger for an output or calcfrom shiny.express import ui, render, input
from shiny import reactive
ui.input_text("input_txt", "Enter text")
ui.input_action_button("send", "Enter")
@render.text
@reactive.event(input.send)
def output_txt():
return input.input_txt()
Important
@reactive.event
overrides the usual implicit dependency detection with an explicit trigger@reactive.calc
@reactive.event
is often used with action buttons or action linksAgenda
Reactive calculations
Your turn
Overriding reactivity
Side effects
@reactive.calc
@reactive.event
ui.show_modal
which triggers a modal window.@reactive.effect
decorator allows you to react to an input without returning a value@reactive.event
Code that produces:
Desired effect | Code |
---|---|
an output | @render_* |
an intermediate value | @reactive.calc |
only side effects | @reactive.effect |
Caution
Code that produces a value and a side effect: Don’t do this!
The “command-query separation” principle