Commit eeeed147 authored by Andrii Grynenko's avatar Andrii Grynenko Committed by Facebook Github Bot

Lambda

Summary: Introduce a coro::lambda helper which makes it safe to create coroutine lambdas with captures.

Reviewed By: lewissbaker

Differential Revision: D13473068

fbshipit-source-id: a1177b4d57715b10fc4398fa6626ee105a8a43ce
parent 9cdc9990
......@@ -155,5 +155,14 @@ TimedWaitAwaitable<std::decay_t<Awaitable>> timed_wait(
std::forward<Awaitable>(awaitable), duration);
}
/// This helper method is a safe way to instantiate a coroutine using a
/// coroutine lambda. It provides a guarantee that the lambda will always
/// outlive the coroutine which it returned.
/// Otherwise, using any lambda captures in the coroutine body is not safe.
template <typename Lambda>
std::result_of_t<Lambda()> lambda(Lambda f) {
co_return co_await f();
}
} // namespace coro
} // namespace folly
......@@ -343,4 +343,23 @@ TEST(Coro, MoveOnlyReturn) {
.getVia(&executor);
EXPECT_EQ(42, *value);
}
TEST(Coro, lambda) {
ManualExecutor executor;
Promise<folly::Unit> p;
auto coroFuture =
coro::lambda([f = p.getSemiFuture()]() mutable -> coro::Task<void> {
(void)co_await std::move(f);
co_return;
})
.scheduleOn(&executor)
.start();
executor.run();
EXPECT_FALSE(coroFuture.isReady());
p.setValue(folly::unit);
executor.run();
EXPECT_TRUE(coroFuture.isReady());
}
#endif
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment