Created
April 9, 2026 03:30
-
-
Save Frityet/467cf971b61ec937e28075d0d1c2a2df to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #import <stdio.h> | |
| #import "AsyncRuntime.h" | |
| #pragma clang assume_nonnull begin | |
| @namespace(Utilities) | |
| + (Promise *)delayForSeconds: (OFTimeInterval)seconds onScheduler: (AsyncScheduler *)scheduler; | |
| @end | |
| @implementation Utilities | |
| + (Promise *)delayForSeconds: (OFTimeInterval)seconds onScheduler: (AsyncScheduler *)scheduler | |
| { | |
| PromiseResolver *resolver = [[PromiseResolver alloc] init]; | |
| OFDate *fireDate = [[OFDate alloc] initWithTimeIntervalSinceNow: seconds]; | |
| OFTimer *timer = [[OFTimer alloc] initWithFireDate: fireDate interval: 0 repeats: false block: ^(OFTimer *unusedTimer) { | |
| (void)unusedTimer; | |
| [resolver resolve: AsyncUnit.unit]; | |
| }]; | |
| [scheduler.runLoop addTimer: timer forMode: scheduler.mode]; | |
| return resolver.promise; | |
| } | |
| @end | |
| @interface App : OFObject<OFApplicationDelegate> @end | |
| @implementation App | |
| - (void)applicationDidFinishLaunching: (OFNotification *)notification | |
| { | |
| (void)notification; | |
| AsyncScheduler *scheduler = [[AsyncScheduler alloc] initWithRunLoop: $assert_nonnil(OFRunLoop.currentRunLoop)]; | |
| Task<OFString *> *greetingTask = [[Task alloc] initWithScheduler: scheduler schedulingBlock: ^OFString *(Task<OFString *> *) { | |
| puts("Greeting task: waiting for timer"); | |
| [[Utilities delayForSeconds: 0.10 onScheduler: scheduler] await]; | |
| puts("Greeting task: resolved"); | |
| return @"hello from the ObjFW run loop"; | |
| }]; | |
| Task *counterTask = [[Task alloc] initWithScheduler: scheduler schedulingBlock: ^AsyncUnit *(Task *) { | |
| for (int i = 0; i < 3; i++) { | |
| printf("Counter task: step %d\n", i); | |
| [[Utilities delayForSeconds: 0.15 onScheduler: scheduler] await]; | |
| } | |
| return AsyncUnit.unit; | |
| }]; | |
| (void)[[Task alloc] initWithScheduler: scheduler schedulingBlock: ^AsyncUnit *(Task *) { | |
| @try { | |
| OFString *greeting = greetingTask.await; | |
| [counterTask await]; | |
| printf("Watcher task: %s\n", greeting.UTF8String); | |
| [OFApplication terminate]; | |
| } @catch (OFException *exception) { | |
| fprintf(stderr, "Demo failed: %s\n", exception.description.UTF8String); | |
| [OFApplication terminateWithStatus: 1]; | |
| } | |
| return AsyncUnit.unit; | |
| }]; | |
| } | |
| @end | |
| #pragma clang assume_nonnull end | |
| OF_APPLICATION_DELEGATE(App); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment