Reactive programming- ex
Published by onesixx on
import random
from shiny import App, Inputs, Outputs, Session, reactive, render, ui
app_ui = ui.page_fluid(
ui.markdown(
f"""
3가지 방법을 통해 `@reactive.event()`를 사용하여, 실행을 제한하는 방법을 보여주는 예제\\
아래 방법 모두 0.5초마다 업데이트되는 임의의 값에 따라 결과가 달라진다.
1) `@render` 함수,
2) `@reactive.calc`, 또는
3) `@reactive.effect`.
버튼이 클릭될 때만 출력이 업데이트되고,
임의의 값은 {ui.output_ui("my_random_num", inline=True)}이다.
"""
),
ui.row(
ui.column(3,
ui.input_action_button("btn_1_out", "(1) Update number"),
ui.output_text("out_out"),
),
ui.column(3,
ui.input_action_button("btn_1_ui", "(1-1) number"),
ui.output_ui("out_ui"),
),
ui.column(3,
ui.input_action_button("btn_2_calc", "(2) Show 1/number"),
ui.output_text("out_calc"),
),
ui.column(3,
ui.input_action_button("btn_3_effect", "(3) Log number"),
ui.div(id="out_effect"),
),
),
)
def server(input: Inputs, output: Outputs, session: Session):
# 매 .5초마다 random number 생성
rct_curr_val = reactive.value(7)
@reactive.effect
def _():
reactive.invalidate_later(0.5)
rct_curr_val.set(random.randint(0, 1000))
@render.ui
def my_random_num():
return rct_curr_val.get()
### ------ 1. @render ------
@render.text
@reactive.event(input.btn_1_out)
def out_out():
print(f"input.btn_1_out: {input.btn_1_out()}")
return str(rct_curr_val.get())
@render.ui
@reactive.event(input.btn_1_ui)
def out_ui():
return ui.p("current number is ", rct_curr_val.get())
### ------ 2. @calc ------
@reactive.calc
@reactive.event(input.btn_2_calc)
def calc():
print("Calculating 1 / rct_curr_val.get()")
return 1 / rct_curr_val.get()
@render.text
def out_calc():
return str(calc())
### ------ 3. effect ------
@reactive.effect
@reactive.event(input.btn_3_effect)
def _():
ui.insert_ui(
ui.p("current number is ", rct_curr_val.get()),
selector="#out_effect",
)
app = App(app_ui, server)