swift-request icon indicating copy to clipboard operation
swift-request copied to clipboard

`async`/`await` support

Open carson-katri opened this issue 2 years ago • 0 comments

The basic idea is that you can await any Request using call():

let getTodos = AnyRequest<[Todo]> {
  Url("todos.com/api")
}
let todos = try await getTodos.call()

callAsFunction could also be added to simplify this demo to:

let todos = try await getTodos()

This opens up new opportunities for crafting readable APIs:

enum API {
  // These can be used as async throwing functions:
  static let getPosts = AnyRequest<[Post]> {
    Url("...")
  }
  static let getUsers = AnyRequest<[User]> {
    Url("...")
  }
  // Real functions can also be added:
  static func getPost(id: Int) async throws -> Post {
    try await AnyRequest<Post> {
      Url(".../\(id)")
    }()
  }
}

// Simply use these as functions:
let posts = try await API.getPosts()
let users = try await API.getUsers()
let post = try await API.getPost(id: 0)

async let gives the power of concurrency:

async let posts = API.getPosts()
async let users = API.getUsers()
let authored = zip(try await callTodos, try await callAsFunctionTodos)

carson-katri avatar Jan 01 '22 22:01 carson-katri