Skip to content

Raw Generator in LazyCollection::make() is not lazy #33297

Answered by JosephSilber
sebsel asked this question in General
Discussion options

You must be logged in to vote

The documentation does not say nor suggest that you can pass a Generator to the LazyCollection's make method.

But this keeps on coming up every now and then, so maybe we should document it properly somewhere.


I think Laravel can handle this for me?

I don't think it can, since iterators (AKA Generators) aren't rewindable.


With your proposed solution:

public function __construct($source = null)
{
    if ($source instanceof Generator) {
        $this->source = function () use ($source) {
            yield from $source;
        };
    }
    // other options omitted for brevity...
}

...this code will break:

$collection->first() == $collection->first(); // false :(

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by sebsel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
3 participants
Converted from issue

This discussion was converted from issue #33297 on June 22, 2020 13:48.