ReactiveX / RxPHP

Reactive extensions for PHP

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Observable from function

nicraMarcin opened this issue · comments

Hi,

$devices = ['192.168.10.11','192.168.10.21','192.168.10.22','192.168.10.23', ...];

function getSnmp($ip, $community, $oid) {
 $snmp = new SNMP(SNMP::VERSION_2C, $ip, $community);
  return $res = $snmp->get($oid);
}

foreach ($devices as $device){
 return getSnmp($device['ip'], public, 'OID');
}

I have this synchronous code. I'm trying various methods to create this as asynchronous but I couldn't manage with it.
Could anybody help me create observable from this function getSnmp() ?

@nicraMarcin if SNMP() is not async, RxPHP won't make it async.

I know that SNMP isn't async but snmp is only example and this can be any function which takes some time to execute. for example http (curl) or something like that:

function test($x) {
  sleep(rand(1,10);
  return uniqd();
}
foreach ($array as $a){
  $res = test($a);
  // do anything with result
}

so this is sync code. with async I don't want to wait for previous function ends but execute another, subscribe and wait for results, like in RxJS and HttpClient I execute request, do next stuff and wait for response to come and do something with recieved data.

executing function once there is no sense to make this async because in a result I have to wait for a result. but when this function is executing x times in a loop (foreach in this case) async make sense because many functions will execute in almost the same time.

Is it possible to make function observable?

RxPHP will not help you make synchronous code asynchronous. It's simply a library that allows you to compose synchronous or asynchronous streams.

You might want to look into swoole