2021-12-10

Tech Programing

程式人小天地

Not receiving value from PassthroughSubject on second try

1 min read


i am using combine to send values from view model class to view class. the code for viewmodel class is down below

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 is down below

 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 1 st button press i am receiving the value and event in viewcontroller class but when i try to press the button again the execution ends in viewmodel class and i am not receiving any events in view controller class. Any help is appreciared.



Source link

資料來源:Stackoverflow

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *