Question

THis is a followup from Use of futures for async loading

My WebGL/Dart program needs to create lots of opengl data while initializing. It all gets loaded asynchronously and uses futures to process data when it is loaded and to know when all the required data is loaded.

I'm having trouble loading textures though. I have this code -

ImageElement img = new ImageElement();
img.onLoad.listen((e) {
  baseTexture = gl.createTexture();
  gl.bindTexture(TEXTURE_2D, baseTexture);
  gl.texImage2DImage(TEXTURE_2D, 0, RGBA, RGBA, UNSIGNED_BYTE, img);
  gl.texParameteri(TEXTURE_2D, TEXTURE_MIN_FILTER, LINEAR);
  gl.texParameteri(TEXTURE_2D, TEXTURE_MAG_FILTER, LINEAR);
});

img.src = "base.png";

This works fine. It loads the image and makes a texture from it when it arrives. However I need my main program to know when all my textures have arrived. Based on the previous question, I should use a future for each one and the use Future.wait to wait for them all to be ready.

However loading images as above doesn't use futures, it uses a StreamSubscription so I get no future back from this function to wait for.

How can I get a future object that will let me know when my texture is creater? Can I create my own Future object and "signal" it in the callback? If I can do that it's not at all clear to me from the documentation how I do that.

Was it helpful?

Solution

You can indeed "signal" that a future is complete manually.

Future<Results> costlyQuery() {
  var completer = new Completer();

  database.query("SELECT * FROM giant_table", (results) {
    // when complete
    completer.complete(results);
  });

  // this returns essentially immediately,
  // before query is finished
  return completer.future; 
}

The future completes when completer.complete(results); is executed.

From here: http://blog.sethladd.com/2012/03/using-futures-in-dart-for-better-async.html

OTHER TIPS

You can use the property Future<T> first of the Stream class. https://api.dartlang.org/docs/channels/stable/latest/dart_async/Stream.html#first

ImageElement img = new ImageElement();
Future future = img.onLoad.first.then((e) {
   ...
});
img.src = "base.png";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top