Re: [Vala] Need help in async methods



Hello Marcin,

When I need a sync wrapper around async method, I generally do
something like this:

public bool dosomething() {
  var result = false;
  var loop = new MainLoop();

  dosomething_async.begin((obj, res) => {
    result = dosomething_async.end(res);
    loop.quit();
  });

  loop.run(); // wait until async method finishes
  return result;
}

Best,

Jiri Janousek

On Sat, Jan 16, 2016 at 3:56 PM, marcin saepia net <marcin saepia net> wrote:
Hello,

I am trying to create a function is synchronous and block for the outer
world, but internally

a) does nothing unless certain callback is called
b) does not block mainloop

Something like synchronous HTTP calls in libsoup - you do request, the
execution if caller is stopped until it's done, the result is just returned
but internally it does asynchronous operations and does not block the whole
program.


I read tutorial and samples but I still struggle to find the valid pattern,
I came to the point that looks more less like this:

public class MyClass : Object {
  private OtherClass other;
  private SourceFunc other_callback;
  private bool       other_result;


  public bool dosomething() {
    // What should I put here to block callee and call dosomething_async
asynchronously?
  }


  public async bool dosomething_async() {
    this.other = new OtherClass();
    this.other.finished.connect(on_other_finished);

    this.other_callback = dosomething_async.callback;
    yield;
    // Now everything except the callee should continue execution
    // unless OtherClass sends us a callback
  }
}


private void on_other_finished(bool result) {
  // Task is finished, should unblock dosomething();
  this.other_result = result;
  this.other_callback();
}


int main(string[] argv) {
  var instance = new MyClass();
  var result = instance.dosomething(); // <-- this should block

  return 0;
}


Thank you for your help

m.
_______________________________________________
vala-list mailing list
vala-list gnome org
https://mail.gnome.org/mailman/listinfo/vala-list


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]