阻塞直到字段被初始化
Block until field is initialized
试图在 setter 内阻止执行,直到提交的值发生变化,我知道它会在几微秒内发生变化,以证明我写的问题:
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);
引起了 Whosebug,知道如何在 setter 中正确地做到这一点吗?
基本上我希望 setter 到 return 初始化时的值,它永远不会 return null。
这是不可能的。
Dart 是单线程的。如果您停止执行,则无法执行更新字段的代码。
如果你想要这样的东西,你需要切换到异步执行。
导入'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;
}
我不认为这个 Future.delayed()
适合此用例的设计。它应该以 Store.x
在值更改时触发事件或完成未来的方式实现。
试图在 setter 内阻止执行,直到提交的值发生变化,我知道它会在几微秒内发生变化,以证明我写的问题:
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);
引起了 Whosebug,知道如何在 setter 中正确地做到这一点吗?
基本上我希望 setter 到 return 初始化时的值,它永远不会 return null。
这是不可能的。 Dart 是单线程的。如果您停止执行,则无法执行更新字段的代码。
如果你想要这样的东西,你需要切换到异步执行。
导入'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;
}
我不认为这个 Future.delayed()
适合此用例的设计。它应该以 Store.x
在值更改时触发事件或完成未来的方式实现。