Skip to content

Commit

Permalink
Add coro into the future example api
Browse files Browse the repository at this point in the history
  • Loading branch information
schloerke committed Mar 23, 2021
1 parent 28bc58c commit 4f4592a
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 9 deletions.
1 change: 1 addition & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ Suggests:
yaml,
feather,
future,
coro,
rstudioapi,
mockery (>= 0.4.2)
RoxygenNote: 7.1.1
Expand Down
56 changes: 47 additions & 9 deletions inst/plumber/14-future/plumber.R
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@

library(promises)
library(future)

library(coro)
future::plan("multisession") # a worker for each core
# future::plan(future::multisession(workers = 2)) # only two workers


# Quick manual test:
# Within 10 seconds...
# 1. Visit /future
Expand All @@ -24,8 +24,8 @@ function() {
#' @get /future
function() {

future({
# perform large computations
future_promise({
# perform long running computations
Sys.sleep(10)

# print route, time, and worker pid
Expand All @@ -34,6 +34,43 @@ function() {
}


# A function that will return a promise object
calc_using_promise <- function() {
# Executes using `future`
future_promise({
# perform long computations
Sys.sleep(1)

# return which process id was used
Sys.getpid()
}) %...>% {
exec_pid <- .
main_pid <- Sys.getpid()
# print route, time, and worker pid
paste0("/coro; ", Sys.time(), "; exec pid:", exec_pid, "; main pid:", main_pid)

list(exec_pid = exec_pid, main_pid = main_pid)
}
}

#' For more info about `coro`, visit https://coro.r-lib.org
#' @contentType text
#' @serializer json list(auto_unbox = TRUE)
#' @get /coro
async(function() {

# (a)wait for the promised value and use as a regular value
# No neeed for a followup promise when using `await(p)`
pids <- await(calc_using_promise())

# Write code with the finalized async value as if it was synchronously found
pids$exec_is_even <- pids$exec_pid %% 2 == 0

# return info
pids
})


# -----------------------------------


Expand All @@ -43,7 +80,7 @@ function() {
#' @param a number
#' @param b number
function(a = NA, b = NA) {
future({
future_promise({
a <- as.numeric(a)
b <- as.numeric(b)
if (is.na(a)) stop("a is missing")
Expand All @@ -59,23 +96,24 @@ function(a = NA, b = NA) {
#' @param a number
#' @param b number
function(a = NA, b = NA) {
future({
future_promise({
a <- as.numeric(a)
b <- as.numeric(b)
if (is.na(a)) stop("a is missing")
if (is.na(b)) stop("b is missing")
if (b == 0) stop("Cannot divide by 0")

a / b
}) %>%
}) %...!%
# Handle `future` errors
promises::catch(function(error) {
{
error <- .
# handle error here!
if (error$message == "b is missing") {
return(Inf)
}

# rethrow original error
stop(error)
})
}
}

0 comments on commit 4f4592a

Please sign in to comment.