Which event loop should I use in Swift NIO?

588 views Asked by At

The example in the docs shows an existing reference to the EventLoop for use with creating a future.

func getNetworkData(args) -> EventLoopFuture<NetworkResponse> {
    let promise = eventLoop.makePromise(of: NetworkResponse.self)
    queue.async {
        . . . do some work . . .
        promise.succeed(response)
        . . . if it fails, instead . . .
        promise.fail(error)
    }
    return promise.futureResult
}

In my case, I don't have access to the current EventLoop. Is there an easy way to get access to it?

Alternatively, I have access to an EventLoopGroup and I can use services.lambda.client.eventLoopGroup.next() to get an EventLoop. Does that just create extra overhead though? Should I be looking for an existing EventLoop?

1

There are 1 answers

0
RobMac On

There's a lot of questions in your question. So I'll answer what I consider the main question:

I don't have access to the current EventLoop. Is there an easy way to get access to it?

You initialize an EventLoopGroup as follows, you only need one per application. Also, depending on your usage you may typically only use 1 thread in numberOfThreads or for heavy usage, go with System.coreCount and it will use all available cores.

import NIO

let eventGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)

At that point .next() yields an eventLoop for you to use and when your future is complete, it returns for shared re-use.

At the end of your application, you shutdown as follows:

try eventGroup.syncShutdownGracefully()

A few notes about this:

  1. If you are using a framework, such as Vapor, the framework already setup the eventGroup for you. Use their own, they do the setup and shutdown for you.

  2. You mention services.lambda.client.eventLoopGroup.next(), so you may be using AWS Lambda? I'm not familiar with it, but if they provide an loop group, as in point 1, use that instead.