alibaba / async_simple

Simple, light-weight and easy-to-use asynchronous components
Apache License 2.0
1.69k stars 251 forks source link

Extend collect any #371

Closed qicosmos closed 7 months ago

qicosmos commented 8 months ago

Why

extend collectAny with callback, similar with go/kotlin select coroutine function.

What is changing

add two new collectAny methods

Example

collectAny with variadic callback functions:

    auto test0 = []() -> Lazy<Unit> { co_return Unit{}; };
    auto test1 = []() -> Lazy<int> { co_return 42; };
    auto test2 = [](int val) -> Lazy<std::string> {
        co_return std::to_string(val);
    };

    int call_count = 0;
    index =
        syncAwait(collectAny(std::pair{test0(), [&](auto) { call_count++; }},
                             std::pair{test1(),
                                       [&](auto val) {
                                           call_count++;
                                           EXPECT_EQ(val.value(), 42);
                                       }},
                             std::pair{test2(42), [&](auto val) {
                                           call_count++;
                                           EXPECT_EQ("42", val.value());
                                       }}));
    EXPECT_EQ(1, call_count);

collectAny with vector callback function:

    auto test0 = []() -> Lazy<int> { co_return 41; };
    auto test1 = []() -> Lazy<int> { co_return 42; };

    std::vector<Lazy<int>> input;
    input.push_back(test0());
    input.push_back(test1());

    syncAwait(collectAny(std::move(input), [](size_t index, Try<int> val) {
        if (index == 0) {
            EXPECT_EQ(val.value(), 41);
        } else {
            EXPECT_EQ(val.value(), 42);
        }
    }));