Using Alamofire with .publishDecodable

Viewed 1682

I need to use .publishDecodable together with Result, I followed the instructions, but I ran into this error: "generic parameter 't' could not be inferred closure"

enter image description here

@Published var loginModel: [LoginModel] = [LoginModel]()

var cancellation: AnyCancellable?

func request<T: Codable>(_ url: String, method: HTTPMethod = .get, headers: HTTPHeaders? = nil, parameters: Codable? = nil) -> AnyPublisher<Result<T, AFError>, Never> {
    let publisher = AF.request(url, method: method, headers: headers)
        .validate()
        .publishDecodable(type: T.self)
    return publisher.result()
}

 func login(email: String, password: String) {
    let parameters = LoginParameters(
        email: email,
        password: password
    )

    cancellation = request(serverURL + "login", method: .post, parameters: parameters)
        .sink { [self] response in
            switch response {
            case .success:
                loginModel = response.value()
            case .failure(error):
                print(error)
            }
        }
}
1 Answers

You should help the compiler to infer the T type be providing the type of the response that you expect. For example your call to request(_:method:headers:parameters:) function might look like this:

cancellation = request(serverURL + "login", method: .post, parameters: parameters)
    .sink { [self] (response: Result<[LoginModel], AFError>) in
        switch response {
        case .success(let value):
            self.loginModel = value
        case .failure(let error):
            print(error)
        }
    }

Or if you prefer you can specify the return type of the request(_:method:headers:parameters:) function like this:

let publisher: AnyPublisher<Result<[LoginModel], AFError>, Never>
publisher = request(serverURL + "login", method: .post, parameters: parameters)
cancellation = publisher.sink { [self] response in
    switch response {
    case .success(let value):
        self.loginModel = value
    case .failure(let error):
        print(error)
    }
}
Related