Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add async_gen() (async version of gen()) #60

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ S3method(print,coro_generator_instance)
export(as_iterator)
export(async)
export(async_collect)
export(async_gen)
export(async_generator)
export(async_ops)
export(async_sleep)
Expand Down
25 changes: 23 additions & 2 deletions R/async.R
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ await <- function(x) {
#' @export
async_sleep <- function(seconds) {
promises::promise(function(resolve, reject) {
later::later(~ resolve(NULL) , delay = seconds)
later::later(~ resolve(NULL), delay = seconds)
})
}

Expand Down Expand Up @@ -116,13 +116,34 @@ async_sleep <- function(seconds) {
#' # Example usage:
#' if (interactive()) {
#' library(magrittr)
#' generate_stream(1:3) %>% async_map(`*`, 2) %>% async_collect()
#' generate_stream(1:3) %>%
#' async_map(`*`, 2) %>%
#' async_collect()
#' }
#'
#' # coro provides a short syntax `async_gen()` for creating one-off
#' # generator _instances_. It is handy to adapt existing iterators:
#' numbers <- generate_stream(1:10)
#' odds <- async_gen(for (x in await_each(numbers)) if (x %% 2 != 0) yield(x))
#' squares <- async_gen(for (x in await_each(odds)) yield(x^2))
#' greetings <- async_gen(for (x in await_each(squares)) yield(paste("Hey", x)))
#' if (interactive()) {
#' async_collect(greetings) %>% promises::then(print)
#' }
#' @export
async_generator <- function(fn) {
assert_lambda(substitute(fn))
generator0(fn, type = "async_generator")
}

#' @rdname async_generator
#' @param expr A yielding expression.
#' @export
async_gen <- function(expr) {
fn <- new_function(NULL, substitute(expr), caller_env())
generator0(fn, type = "async_generator")()
}

#' @rdname async_generator
#' @inheritParams await
#' @export
Expand Down
19 changes: 18 additions & 1 deletion man/async_generator.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading