Skip to content

Instantly share code, notes, and snippets.

View jacobsapps's full-sized avatar

Jacob Bartlett jacobsapps

View GitHub Profile
@MainActor
func setupUI() async {
await someAsyncWork()
}
@concurrent
func someAsyncWork() async {
// with @concurrent attribute, this runs on the background thread
try? await Task.sleep(for: .milliseconds(100))
}
@MainActor
func setupUI() async {
await someAsyncWork()
}
func someAsyncWork() async {
// Add breakpoint to test this at runtime - it's on the main thread!
try? await Task.sleep(for: .milliseconds(100))
}
actor AuthServiceImpl: AuthService {
var tokenTask: Task<String, Error>?
func getBearerToken() async throws -> String {
if tokenTask == nil {
tokenTask = Task { try await fetchValidAuthToken() }
}
defer { tokenTask = nil }
actor AuthServiceImpl: AuthService {
func getBearerToken() async throws -> String {
if cachedToken.isValid {
return cachedToken
}
return try await authAPI.refreshCredentials() <-- suspension point
}
}
var purgeCacheTask: Task<Void, Never>?
func setupCacheTTL() {
purgeCacheTask?.cancel()
purgeCacheTask = Task(priority: .low) {
try? await Task.sleep(for: .seconds(300))
guard !Task.isCancelled else { return }
cache.clear()
}
}
/// Form task creation flags for use with the createAsyncTask builtins.
@available(SwiftStdlib 5.1, *)
@_alwaysEmitIntoClient
func taskCreateFlags(
priority: TaskPriority?, isChildTask: Bool, copyTaskLocals: Bool,
inheritContext: Bool, enqueueJob: Bool,
addPendingGroupTaskUnconditionally: Bool,
isDiscardingTask: Bool,
isSynchronousStart: Bool
) -> Int {
% if HAS_TASK_EXECUTOR:
/// - taskExecutor: The task executor that the child task should be started on and keep using.
/// Explicitly passing `nil` as the executor preference is equivalent to no preference,
/// and effectively means to inherit the outer context's executor preference.
/// You can also pass the ``globalConcurrentExecutor`` global executor explicitly.
% end
@discardableResult
public ${METHOD_VARIANT}( // Task ${METHOD_VARIANT}
${",\n ".join(adjust_params_for_kind(PARAMS))}
@State private var currentProgress: Double = 0.0
private var percentageLabel: some View {
Text("\(Int(currentProgress * 100))%")
.font(.system(size: 48, weight: .bold, design: .rounded))
.foregroundColor(.white)
}
private var progressBar: some View {
TimelineView(.animation) { context in
struct ProgressKeyframes {
var progress: Double = 0.0
}
@State private var currentProgress: Double = 0.0
@State private var animationStartTime: Date = Date()
private var progressTimeline: KeyframeTimeline<ProgressKeyframes> {
KeyframeTimeline(initialValue: ProgressKeyframes()) {
KeyframeTrack(\.progress) {
KeyframeTrack(\.verticalOffset) {
LinearKeyframe(20, duration: 0.25)
SpringKeyframe(-40, duration: 0.5, spring: .snappy)
CubicKeyframe(0, duration: 0.25)
}