0
function fetchProduct()
{
   $cursor = r\table("tableOne")->changes()->run($conn);

    foreach ($cursor as $product) {
       yield $product;
    }
}


$product = fetchProduct();
var_dump($product);
echo "i"; //when the function use yield, this line executed. But when return used, it doesn't come to this line.

I understand rethinkdb's changes() will keep listening to the changes so i found that its better to use yield over the $cursor. But the yield doesn't return value to the calling party. But when return is used value returned.

How to make the yield to return any value when changes occur?

References:
https://rethinkdb.com/docs/async-connections/
What does yield mean in PHP?

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
112233
  • 2,406
  • 3
  • 38
  • 88
  • The async connections reference doesn't list PHP as implemented for async and as PHP is generally synchronous that would definitely require something like EventMachine or similar in PHP to work. I don't see it working like you tried. – ChristianM Mar 17 '18 at 08:15

1 Answers1

0

When using yield() this effectively makes the function 'return' an iterator. So as per the example you linked 'What does yield mean in PHP?' you need to loop over the return value.

function fetchProduct()
{
    //$cursor = r\table("tableOne")->changes()->run($conn);
    $cursor = range(1,5);
    foreach ($cursor as $product) {
        yield $product;
    }
}


//$product = fetchProduct();
//var_dump($product);
foreach ( fetchProduct() as $product ){
    var_dump($product);
}
echo "i";

In the example above, I've changed it to use range() as the values, but this shows how you can process the return value and the difference between how you were trying to make it work and how it can work.

I would say that I don't know how this works with rethinkdb, but more about how yield() works in general.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55