swiftobservablerx-swiftreactive-cocoa

How to Synchronize or make an Observable wait on Swift?


So, i have this login function, where i want to return a Boolean to my .xib controller, where it has to make some modifications, according to the success of the login.

 func login(cpf: String) -> Bool {
    let url = URL(string: AccessibilityDataAccessProvider.kLoginURL)
    let params = ["username": String.init(describing: cpf)]

    var success = false

    dataAccessProvider.postSimpleResponse(url: url!, params: params)
        .subscribe(onNext: { (userToken) in
            let userData = UserDefaults.standard
            userData.set(userToken, forKey: AccessibilityDataAccessProvider.userTokenKey)
            userData.synchronize()
            success = true
    }, onError: { (error) in
        print("Login Error: \(error)")
    }).disposed(by: disposeBag)

    return success
}

The return from postSimpleResponse() method is an Observable of type Any?.

The thing is, that my login() method is returning before the success boolean variable is set true in the subscribe.

How could i resolve this ?


Solution

  • You can map the Observable to a Bool observable (Although Bool is not necessary here, you can just use Void), and return Observable from login method.

    Like this:

    func login(cpf: String) -> Observable<Bool> {
        let url = URL(string: AccessibilityDataAccessProvider.kLoginURL)
        let params = ["username": String.init(describing: cpf)]
    
        return dataAccessProvider.postSimpleResponse(url: url!, params: params)
            .do(onNext: {
                let userData = UserDefaults.standard
                userData.set(userToken, forKey: AccessibilityDataAccessProvider.userTokenKey)
            })
            .map { _ in
                return true
        }
    }
    

    And then observe on it:

    login(cpf: "data").subscribe(onNext: { _ in
        // Success
    }, onError: { _ in
        // Failure
    }).disposed(by: disposeBag)