Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[11.x] Add throttle method to LazyCollection #51060

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

Merged
merged 1 commit into from
Apr 15, 2024

Conversation

JosephSilber
Copy link
Contributor

@JosephSilber JosephSilber commented Apr 14, 2024

Allows throttling the values retrieved from a lazy collection:

LazyCollection::times(3)->throttle(seconds: 1)->each(function ($number) {
    dump($number); // Will dump each number, with a pause (sleep) of about a second in between each...
});

Note: The sleep will not be 1 second. That would be quite naïve. Instead, it includes the time it takes to process each retrieved value, and only sleeps for the remainder of the duration.


Especially useful when interacting with external APIs, which may have some rate limits. Can be used both for pulling data as well as for pushing data.

Pulling data example:

$userIds = collect([1, 2, 3])->lazy();

$users = $userIds
    ->throttle(1)
    ->map(fn ($userId) => API::fetchUser($id));

Or, if the external API supports fetching, say, 50 users at once:

$userIds = collect([1, 2, 3, /* ... */])->lazy();

$users = $userIds
    ->chunk(50)
    ->throttle(1)
    ->map(fn ($userIds) => API::fetchUsers($userIds))
    ->flatten();

Pushing data example:

$userIds = collect([1, 2, 3])->lazy();

$userIds
    ->throttle(1)
    ->each(fn ($userId) => API::deleteUser($id));

Here's a real-world use case, which would be vastly simplified after this PR:

DB::table('stock_sync')->cursor()->throttle(1)->map(function ($sync) {
    // Handle stock sync updates...
});

@JosephSilber JosephSilber force-pushed the throttle-lazy-collection branch from d054967 to 6e69308 Compare April 14, 2024 18:54
@JosephSilber JosephSilber force-pushed the throttle-lazy-collection branch from 6e69308 to aadf9b0 Compare April 14, 2024 19:00
@taylorotwell taylorotwell merged commit ad00a85 into laravel:11.x Apr 15, 2024
@JosephSilber JosephSilber deleted the throttle-lazy-collection branch April 15, 2024 16:04
@timacdonald
Copy link
Member

This is pretty sick.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants
Morty Proxy This is a proxified and sanitized view of the page, visit original site.