Mix async/await with handlers: Access actor from a non async function

I created a server-client setup with SwiftNIO. So far I used, of course, everything with completionHandlers. One specific case, where I now have problems with adding async/await to my project, is the following:

The logic of my server and client is, that they can send a message to each other and they can wait for an answer. I managed this with adding an increasing ID to every message If the server then answer this message, it uses the same ID, so that the client can recognize, that it is the answer.

For this I created kind of a waiting queue, an array with several WaitingQueueObjects (I called them so). Now if there is an incoming message, the client checks, if it fits to a waiting queue object and if so, it calls the handler function provided by the requesting function. In detail:

Call the function
func askAndWaitForMessage<T: Codable>(message: String, content: T?, connection: Connection, messageHandler: MessageHandler) {

Add the messageHandler to the WaitingQueue-array.

If there is an incoming message, check the WaitingQueue-array and if there is the object with the corresponding ID, call the MessageHandler.

Now I want to make askAndWaitForMessage an async-function. That's not such a big deal, because I can use withCheckedThrowingContinuation to call the message handler.

My main problem is now, that I have to put my WaitingQueue-array to an actor, otherwise there will be a data race. But if I do that, I cannot access the actor from the async version of the function.

The only solution I can find now is to convert the whole project to the async function. Unfortunately that's a lot of work and I wish there could be a temporary solution until I could finish that.

Is there any chance to access the actor from a non async function?

I think I found the solution: Is it correct if I put the whole non-async function into a Task { ... }?

Yes, this should be correct. If you need to signal results into NIO you can use promise.completeWithTask as well.

Terms of Service

Privacy Policy

Cookie Policy