FPGA
FPGA

Reputation: 3855

Block until field is initialized

trying to block the execution within a setter until the filed value changes and i know that it will change within a few microseconds, to demonstrate the problem i wrote:

import 'dart:async';

void main() {
  new Timer.periodic(new Duration(seconds:1),(t)=>print(Store.x));
  new Timer.periodic(new Duration(seconds:3),(t)=>Store.x='initialized');
}

class Store{
  static String _x = null;
  static set x(v) => _x=v;
  static get x{
    //how do i block here until x is initialized
    return _x;
  }
}

A while(x==null); caused stackoverflow, any idea how to do this properly within the setter?

basically i want the setter to return the value when its initialized it should never return null.

Upvotes: 1

Views: 88

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657158

This can't be done. Dart is single-threaded. If you stop execution the code updating the field can't be executed.

If you want something like that you need to switch to async execution.

import 'dart:async';

void main() {
  new Timer.periodic(new Duration(seconds:1),(t)=>print(Store.x));
  new Timer.periodic(new Duration(seconds:3),(t)=>Store.x='initalized');
}

class Store{
  static String _x = null;
  static set x(v) => _x=v;
  static Future<String> get x async {
    while(x == null) {
     await new Future.delayed(const Duration(milliseconds: 20), 
    }
    return _x;
  }
}

func someFunc() async {
  var x = await new Store.x;
}

I wouldn't consider this Future.delayed() good design for this use case. It should be implemented in a way that Store.x fires an event or completes a future when the value changed.

Upvotes: 1

Related Questions