I'm new to EventLoop futures and promises. My software stack:
- Backend in Go + gRPC
- iOS client in Swift + SwiftUI + GRPC + NIO
I've got something to work and looking for suggestions on how to improve it since I'm a little lost in docs around .map
, .flatMap
, .always
, etc.
Here's a relevant function from my gRPC data singleton within iOS app:
import Foundation
import NIO
import GRPC
class DataRepository {
static let shared = DataRepository()
// skip ...
func readItem(id: Int64, eventLoop: EventLoop) -> EventLoopFuture<V1_ReadResponse> {
// TODO: Is this the right place?
defer {
try? eventLoop.syncShutdownGracefully()
}
let promise = eventLoop.makePromise(of: V1_ReadResponse.self)
var request = V1_ReadRequest()
request.api = "v1"
request.id = id
let call = client.read(request, callOptions: callOptions) // client - GRPCClient initialized in the singleton
call.response.whenSuccess{ response in
return promise.succeed(response)
}
call.response.whenFailure{ error in
return(promise.fail(error))
}
return promise.futureResult
}
My code in SwiftUI View:
import SwiftUI
import NIO
struct MyView : View {
@State private var itemTitle = "None"
var body: some View {
Text(itemTitle)
}
func getItem() {
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let result = DataRepository.shared.readItem(id: 1, eventLoop: eventLoopGroup.next())
_ = result.always { (response: Result<V1_ReadResponse, Error>) in
let res = try? response.get()
if let resExist = res {
self.itemTitle = resExist.item.title
}
_ = response.mapError{ (err: Error) -> Error in
print("[Error] Connection error or item not found: \(err)")
return err
}
}
}
Should I refactor getItem
and/or readItem
? Any specific suggestions?