@@ -2,6 +2,7 @@ import { OperationCanceledException, Trampoline } from "./AsyncBuilder.ts";
22import { Continuation , Continuations } from "./AsyncBuilder.ts" ;
33import { Async , IAsyncContext , CancellationToken } from "./AsyncBuilder.ts" ;
44import { protectedCont , protectedBind , protectedReturn } from "./AsyncBuilder.ts" ;
5+ import type { IEvent$2 } from "./Event.ts" ;
56import { FSharpChoice$2_$union , Choice_makeChoice1Of2 , Choice_makeChoice2Of2 } from "./Choice.ts" ;
67import { TimeoutException_$ctor } from "./System.ts" ;
78import { Exception } from "./Util.ts" ;
@@ -86,6 +87,23 @@ export function awaitPromise<T>(p: Promise<T>) {
8687 ? conts [ 2 ] : conts [ 1 ] ) ( err ) ) ) ;
8788}
8889
90+ export function awaitEvent < Del extends Function , T > ( event : IEvent$2 < Del , T > , cancelAction ?: ( ) => void ) : Async < T > {
91+ return protectedCont ( ( ctx : IAsyncContext < T > ) => {
92+ let tokenId : number ;
93+ const handler = ( ( _sender : unknown , arg : T ) => {
94+ ctx . cancelToken . removeListener ( tokenId ) ;
95+ event . RemoveHandler ( handler as unknown as Del ) ;
96+ ctx . onSuccess ( arg ) ;
97+ } ) as unknown as Del ;
98+ tokenId = ctx . cancelToken . addListener ( ( ) => {
99+ event . RemoveHandler ( handler ) ;
100+ if ( cancelAction != null ) { cancelAction ( ) ; }
101+ ctx . onCancel ( new OperationCanceledException ( ) ) ;
102+ } ) ;
103+ event . AddHandler ( handler ) ;
104+ } ) ;
105+ }
106+
89107export function cancellationToken ( ) {
90108 return protectedCont ( ( ctx : IAsyncContext < CancellationToken > ) => ctx . onSuccess ( ctx . cancelToken ) ) ;
91109}
0 commit comments