contextdart 0.1.1 contextdart: ^0.1.1 copied to clipboard
golang's `context.Context` implements in dart
import 'package:contextdart/contextdart.dart';
class Hello {}
void main() async {
var ctx = Context.withValue(
Context.background(),
"value will put into context",
key: "some comparable key",
);
ctx = Context.withValue(
ctx,
Hello(),
);
getValueFromContextByKey(ctx);
getValueFromContextByType(ctx);
canceledContext(ctx);
}
getValueFromContextByKey(Context ctx) {
// in deep function;
var v = ctx.value("some comparable key");
// ignore: avoid_print
print(v);
}
getValueFromContextByType(Context ctx) {
// in deep function;
var v = ctx.value<Hello>();
// ignore: avoid_print
print(v);
}
canceledContext(Context ctx) {
var cctx = Context.withCancel(ctx);
// async action
Future.any([
cctx.done()!.first,
Stream.periodic(const Duration(seconds: 1))
.map((e) => Exception("bomb!"))
.first,
]);
// cancel cause something like timeout
cctx.cancel();
}