later
later copied to clipboard
RNG state not preserved in callbacks
The RNG state is not always preserved when executing callbacks. This is similar to rstudio/shiny#1768.
This example sets the value of .Random.seed
in a callback, but it appears to not have an effect:
{
set.seed(100)
oldseed <- .GlobalEnv$.Random.seed
set.seed(1234)
later(function() {
.GlobalEnv$.Random.seed <- oldseed
})
run_now()
}
identical(oldseed, .GlobalEnv$.Random.seed)
# [1] FALSE
If you call httpuv::getRNGState()
in the callback, it fixes the problem. (That function was added to deal with problems just like this).
{
set.seed(100)
oldseed <- .GlobalEnv$.Random.seed
set.seed(1234)
later(function() {
.GlobalEnv$.Random.seed <- oldseed
httpuv::getRNGState()
})
run_now()
}
identical(oldseed, .GlobalEnv$.Random.seed)
# [1] TRUE
When this is fixed, we also need to make sure that it fixes it when the input handler executes the callback. To test it, run this at the console. Just run the first part, wait for a moment, and then run the last line.
set.seed(100)
oldseed <- .GlobalEnv$.Random.seed
set.seed(1234)
later(function() {
.GlobalEnv$.Random.seed <- oldseed
})
# Wait for a moment before running this
identical(oldseed, .GlobalEnv$.Random.seed)