Files
swift-nio/Sources/NIOCore/DispatchQueue+WithFuture.swift
T
Cory Benfield 25da619b78 Extract EventLoop protocols and EventLoopFuture to Core (#1898)
Motivation:

The next step on extracting the base abstractions is to pull out
EventLoop, EventLoopGroup and related types, and also EventLoopPromise
and EventLoopFuture. These types are fundamental to the API.

Modifications:

- Extract EventLoop, EventLoopGroup, and related types.
- Extract EventLoopPromise and EventLoopFuture.
- Add new @testable imports.
- Split MultiThreadedEventLoopGroup into new file, appropriately named.

Result:

Better separation.
2021-07-21 07:56:11 +01:00

48 lines
1.7 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Dispatch
extension DispatchQueue {
/// Schedules a work item for immediate execution and immediately returns with an `EventLoopFuture` providing the
/// result. For example:
///
/// let futureResult = DispatchQueue.main.asyncWithFuture(eventLoop: myEventLoop) { () -> String in
/// callbackMayBlock()
/// }
/// try let value = futureResult.wait()
///
/// - parameters:
/// - eventLoop: the `EventLoop` on which to proceses the IO / task specified by `callbackMayBlock`.
/// - callbackMayBlock: The scheduled callback for the IO / task.
/// - returns a new `EventLoopFuture<ReturnType>` with value returned by the `block` parameter.
@inlinable
public func asyncWithFuture<NewValue>(
eventLoop: EventLoop,
_ callbackMayBlock: @escaping () throws -> NewValue
) -> EventLoopFuture<NewValue> {
let promise = eventLoop.makePromise(of: NewValue.self)
self.async {
do {
let result = try callbackMayBlock()
promise.succeed(result)
} catch {
promise.fail(error)
}
}
return promise.futureResult
}
}