LoginSignup
1

More than 5 years have passed since last update.

eventReactive() と observeEvent() の違いを動作で理解する

Last updated at Posted at 2017-02-07

なんとなくマニュアルを流し読みして理解していた気になっていたのですが、デバッグではまったりして分かったことがあったので記事にしておきます。

概要

Shinyでイベントをモニタして発火する関数としてeventReactive() と observeEvent() があります。マニュアルには以下のように記載してあります。

observeEvent returns an observer reference class object. eventReactive returns a reactive expression object.
observeEventはオブサーバクラスオブジェクトを返し、eventReactiveはリアクテブエクスプレッションを返します

ここで注意なのがreactive valueを作るということはそのreactiveが伝播する範囲を調べ、UI上で使われなければ何も起こらないという動作になります。つまり例えば途中までコードを書いて、「ボタン押したら発火するかな~」的なテストすることはよくありますが、reactive valueがUI上で使われていなければ発火しません。なのでデバッグする時はprint()でコンソールに出すだけはダメで、modalDialogを出したりrenderTextを使用してShinyのUI側にreactiveの作用先を準備してデバッグしましょう。

サンプルコード

6行目がコメントアウトされているとaction_buttonは一切発火しません。
action_button2は常に反応します。

library(shiny)
shinyApp(
  ui = fluidPage(
    actionButton("action_button", "Button1")
    ,actionButton("action_button2", "Button2")
    #,textOutput("text")
  ),
  server = function(input, output) {
    reactive_data <- eventReactive(input$action_button, {
      print("brabra")
      return("brabra_return")
    })
    observeEvent(input$action_button2, {
      print("brabra2")
    })
    output$text <- renderText({reactive_data()})
  }
)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1