Search code examples
rrlang

Option for immediate output of rlang warnings


If I create a warning using the rlang package inside a function, the warning is output after the function output:

delayed_warning <- function() {
  rlang::warn("A warning")
  Sys.sleep(10)
  "A return value"
}

delayed_warning()
#> Warning: A warning
#> [1] "A return value"

Created on 2023-09-18 with reprex v2.0.2

In some circumstances it is useful to output warnings immediately, for example when the warning is to tell the user that a function might take a long time. If I were to use the base-R warning(), I could use immediate. = TRUE to output the warning immediately.

My question: is there a way to output immediately a warning created using rlang::warn()?

(This feels like the sort of thing that I should have been able to answer with a Google search, so I suspect I'm not searching for the right terms.)


Solution

  • After doing some further digging I found a GitHub issue requesting exactly this functionality in rlang. The issue has been closed with a note saying there is no plan to provide this.

    Since outputting a warning immediately isn't possible using rlang::warn(), it seems the best workaround (as posted by @TimTeaFan in a comment) is to instead use rlang::inform(), since messages are produced immediately by default:

    instant_message <- function() {
      rlang::inform("A message")
      Sys.sleep(10)
      "A return value"
    }
    
    instant_message()
    #> A message
    #> [1] "A return value"
    

    Created on 2023-09-20 with reprex v2.0.2