Skip to content

Instantly share code, notes, and snippets.

@alebianco
Created August 19, 2015 14:19
Show Gist options
  • Save alebianco/24d2dee448dd90cae24f to your computer and use it in GitHub Desktop.
Save alebianco/24d2dee448dd90cae24f to your computer and use it in GitHub Desktop.
Tink Streams
package ;
import tink.core.Callback;
import tink.core.Outcome;
import tink.core.Future;
@:expose("game")
@:keep
class Main {
public static var instance:Main;
var deferred = new StreamTrigger<Int>();
var stream:Future<Int>;
var handler:CallbackLink;
public function new() {
stream = deferred.asFuture();
}
public function attach():Void {
handler = stream.handle(onMessage); // can resolve multiple times
// handler = (stream >> function(v:Int) return v * 10).handle(onMessage); // resolves only once
}
public function detach():Void {
handler.dissolve();
}
public function resolve(value:Int):Void {
deferred.trigger(value);
}
public function loop(value:Int):Void {
attach();
resolve(value);
detach();
}
function onMessage(value:Int):Void {
trace(value);
}
static function main() {
instance = new Main();
}
}
class StreamTrigger<T> {
var result:T;
var list:CallbackList<T>;
var future:Stream<T>;
public function new() {
this.list = new CallbackList();
future = new Stream(
function (callback)
return
if (list == null) {
callback.invoke(result);
null;
}
else list.add(callback)
);
}
public inline function asFuture() return future;
public inline function close() {
this.list.clear();
this.list = null;
}
public inline function trigger(result:T):Bool
return
if (list == null) false;
else {
var list = this.list;
this.result = result;
list.invoke(result);
true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment