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

async/await and AsyncSequence Prototype

Open dnadoba opened this issue 4 years ago • 1 comments

Just noticed that SwiftNIO has basic support for async/await 🎉 The PR is not meant to be merged. Just a quick outlook into the future.

The internal implementation is really ugly but it works and the call site looks really nice:

let bootstrap = ClientBootstrap(
    config: ClientSetupConfig(
        timeBetweenKeepaliveFrames: 0,
        maxLifetime: 30_000,
        metadataEncodingMimeType: "message/x.rsocket.routing.v0",
        dataEncodingMimeType: "application/json"
    ),
    transport: WSTransport(),
    timeout: .seconds(30)
)
let client = try await bootstrap.connect(host: host, port: port, uri: uri)

let stream = client.requester.requestStream(payload: Payload(
    metadata: route("searchTweets"),
    data: Data(searchString.utf8)
))

for try await payload in stream.prefix(limit) {
    let json = try JSONSerialization.jsonObject(with: payload.data, options: [])
    let data = try JSONSerialization.data(withJSONObject: json, options: [.prettyPrinted])
    let string = String(decoding: data, as: UTF8.self)
    print(string)
}

Take a look at Sources/Examples/AsyncTwitterClient/main.swift if you want to see how async/await could look like for RSocket. The complete implementation is in Sources/RSocketAsync/AsyncAwait.swift.

If you want to play around with it, you need a download a snapshot from https://swift.org/download/#snapshots with the lates changes from the main branch. async/await is available since Swift 5.4 and AsyncSequence only in Swift 5.5. As even Swift 5.4 is not yet release, this is highly experimental.

dnadoba avatar Apr 03 '21 02:04 dnadoba

The API looks very nice!

nkristek avatar Apr 06 '21 10:04 nkristek