Not receiving value from PassthroughSubject on second try

Viewed 473

I am using Combine to send values from a view model to a view. The code for view model class:

var subject = PassthroughSubject<User,Error>()
func validate login(username: String, password: String){
    let url = "someurl"
    let httpRequest = MerchantLogin(username: username, password: password)
    let httpBody = try! JSONEncoder().encode(httpRequest)
    cancellable = webservice.apiRequest(url: URL(string: url)!, resultType: User.self, httpMethodType: .post, requestBody: httpBody)
    receive(on: RunLoop.main)
        .sink { [weak self]completion in
            switch completion{
            case .failure(let error ):
                 print(error)
                 self?.subject.send(completion:.failure(error))

            case .finished :
                 print("finished")
            }
            
        } receiveValue: { user in
            self.subject.send(user)
            
        }
}

code for view class:

private var binding = Set<AnyCancellable>()
var viewModel: LoginViewModel!

override func viewDidLoad() {
    super.viewDidLoad()
    setupBinding()
}
func setupBinding(){
    viewModel.subject
        .receive(on: RunLoop.main)
        .sink { [weak self] completion in
            switch completion{
                
            case .finished:
                print("")
            case .failure(let error):
               
                let message = "\(error)"
                self?.presentAlert(withTitle: "Oh snap!", message: message)
            }
        } receiveValue: { [weak self] user in
           print(user)
        }.store(in: &binding) 
}   

@IBAction func loginAction(_ sender: Any) {
    self.viewModel.validateLogin(username: self.usernameTextFiled.text!, password: self.passwordTextField.text!)
}

On the first button press I am receiving the value and event in the view controller but when I try to press the button again the execution ends in the view model and I am not receiving any events in the view controller.

0 Answers
Related