简体   繁体   中英

How to Wait async api response using Alamofire and Rxswift?

I have a question about the async api.
May I wait async api to get the response?
In my case, I want when "isAgreen == true" and show alertcontroller to user.
I dont know how to do it.
Thanks.

Class UserModel:NSObject { 

var isAgree:Bool?

func put(_ params:[String:Any], _ callback: @escaping (JSON) -> Void){

let url = self.customUrl(params)
self.requestJSON( .put, url: url, params: params, callback: { json in
  callback(json)
})
}

func getStatus() {

   API.getUserStatus.put(params, { json in

      guard json["status"] != "error" else {

          if json["error"] == "friend agree" {

              self.isAgreen = true

              self.friendship.updateDatabase()
          }
          return
      }
    })
  }
}


class FriendInfoViewController: UIViewController {

func buttonClick(sender:UIButton) {

   let user:UserModel = UserModel()
   user.getStatus()

   if user.isAgreen == true{ //Wait to response and show alertViewController

        let alert = showAlert(title: "Warning", message: "Test", style: .alert)
        self.present(alert, animated: true, completion: nil)
     }
   }
}

You can Implement your Functionality with Reactive way(RxSwift) like below.

func getStatus() -> Observable<Bool> {

        return Observable.create({ (observer) -> Disposable in

            API.getUserStatus.put(params, { json in

                guard json["status"] != "error" else {

                    if json["error"] == "friend agree" {

                        observer.onNext(true)
                        self.friendship.updateDatabase()
                    } else {
                        observer.onNext(false)
                    }
                }
               observer.onNext(true)

                //Error event which occurred in your request
                //observer.onError(Error)

                observer.onCompleted()
            })

            return Disposables.create()
        })
    }

And you cant get result By calling like below:

let user:UserModel = UserModel()
let bag = DisposeBag()

user.getStatus().subscribe(onNext: { (isAgreen) in
            if isAgreen {
                let alert = showAlert(title: "Warning", message: "Test", style: .alert)
                self.present(alert, animated: true, completion: nil)
            }

        }, onError: { (error) in
            //Do stuff when error Event occurred
        }, onCompleted: { 
            //Do stuff when Complete Event occurred
        }).addDisposableTo(bag)

Hope will help you.

Hey you should not set a global variable. Instead of that use a comletionHandler in the get Status Method. It could look like:

func getStatus(_ completionHandler: @escaping (Bool) -> Void) {

    API.getUserStatus.put(params, { json in

        guard json["status"] != "error" else {

            if json["error"] == "friend agree" {


                self.friendship.updateDatabase()
                completionHandler(true)
            }
            completionHandler(false)
        }
        completionHandler(true)
    })
}

The call would look like:

user.getStatus() { isAgreen in
    if isAgreen {
        // do your stuff if user is logged in
    } else {
        // do your stuff if not logged in
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM