Reactive programming

Published by onesixx on

https://shiny.posit.co/py/docs/reactive-programming.html

from shiny import App, render, ui

app_ui = ui.page_fluid(
    ui.h2("Hello Shiny!"),
    ui.input_slider("n", "N", 0, 100, 20),
    ui.output_text_verbatim("txt"),
)

def server(input, output, session):
    @output
    @render.text
    def txt():
        return f"n*2 is {input.n() * 2}"

app = App(app_ui, server)
from shiny import App, render, ui, reactive

app_ui = ui.page_fluid(
    ui.h2("Hello Shiny!"),
    ui.input_slider("n", "N", 0, 100, 20),
    ui.output_text_verbatim("txt"),
)

def server(input, output, session):
    @reactive.calc
    def reactive_result():
        return input.n() * 2

    @output
    @render.text
    def txt():
        return reactive_result()

app = App(app_ui, server)

기본 Reactive 프로그래밍: (reactive) input이 수정되면 (reactive) output 함수를 다시 실행
Shiny는 이를 자동으로 수행하며, 특정 값이 변경될 때 함수를 명시적으로 다시 실행할 필요가 없습니다.

좀 더 복잡한 reactive를 활용해 보면

  • reactive.Value:
    value가 변경될 때, reactive함수를 실행시키는 객체
    An object that causes reactive functions to run when its value changes.

    – show_markers = reactive.Value(False)
    – zip_selected = reactive.Value(None)
    – selected_table_row = reactive.Value(pd.DataFrame())

    ==>
    zip_selected._value
    selected_table_row._value

  • reactive.Calc:
    return값으로 사용되는 반응형 함수를 생성
    Create a reactive function that is used for its return value.

@reactive.Calc
def zips_in_bounds():
input.aa
return

@reactive.Calc
def zips_marker_color():
read_reactive()
return

reactive.effect

  • reactive.Effect:
    부작용에 사용되는 반응형 함수를 생성합니다. 반환 값이 아닌 부작용 자체에 관심이 있습니다.
    Create a reactive function that is used for its side effects (and not its return value).

@reactive.Effect
def _():
nzips = zips_in_bounds().shape[0]
show_markers.set(nzips < 200)

@reactive.Effect
@reactive.event(input.variable)
def _():

  • @output: outputs (wrapped up in a reactive.Effect)

There are a few utility functions that help with managing reactivity:

  • with isolate(): Run blocks of code inside a reactive function, but without taking a reactive dependency on code inside the block.
  • @reactive.event(): A decorator that controls what causes a reactive function to invalidate.

@output(id=”density_pop”)
@render_widget
def _():
return density_plot(

Categories: shiny

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x