How to cancel a long polling request with PromiseKit and Moya

1.1k views Asked by At

I'm using PromiseKit and Moya to send a long polling request in the method bellow:

func pullMessages() {

    let service = ChatServices()
    let request = service.pullMessages()
    self.request = request
    request.promise.then { [weak self] status -> Void in

        // If chat successfully established with the agent
        // navigate to chat screen or else try again. And if failure then show error message

        guard let `self` = self else { return }

        switch status {

        case .waiting:
            self.pullMessages()

        case .messages(let messages):
            for message: String in messages {
                self.addMessage(text: message, sender: self.agentSender())
            }
            self.pullMessages()

        case .chatEnded(let reason):
            if reason  == .agent {
                self.endChat(with: "Agent ended chat session")
            }

        case .failure:
            self.endChat(with: "Session lost")
        }

        }.catch { error in
            // Show error
            Log.warning(error.localizedDescription)
            self.endChat(with: "Session lost")
    }

}

And I'm using self.request to cancel the request once I'm leaving the view in viewWillDisapear. But after I leave the view, and a new message arrives. the "cancelled" request returns the message. Any ideas why this is happening?

0

There are 0 answers