Search code examples
iosswiftreactive-cocoa

RACCommand Confusion


I'm attempting to use RACCommand on my PasswordResetViewController. In my viewDidLoad I have the following:

sendButtonItem = UIBarButtonItem(title: "Reset Password", style: .Done, target: self, action: nil)

var emailIsValid = textField.rac_textSignal().map { text -> AnyObject! in
    return count((text as! String)) > 0
}

let passwordResetSignal = RACSignal.createSignal { (subscriber) -> RACDisposable! in
    User.requestPasswordResetForEmailInBackground(self.textField.text) { success, error in
        if success {
            subscriber.sendNext(success)
            subscriber.sendCompleted()
        } else {
            subscriber.sendError(error)
        }
    }

    return nil
}

sendButtonItem.rac_command = RACCommand(enabled: emailIsValid) { (input) in
    return passwordResetSignal
}

sendButtonItem.rac_command.executionSignals.subscribeError { (error) -> Void in
    println("ERROR!")
}

sendButtonItem.rac_command.executionSignals.subscribeNext { (success) -> Void in
    println("SUCCESS!")
}

navigationItem.rightBarButtonItem = sendButtonItem

The rightBarButtonItem enables/disables as I expect but I'm not getting any next or error events.


Solution

  • The executionSignals is a signal of signals. In other words: each time the command is executed, it sends command's signal (in your case, passwordResetSignal) as its next value.

    If you want to subscribe for values sent from the passwordResetSignal, use switchToLatest:

    sendButtonItem.rac_command.executionSignals.switchToLatest().subscribeNext { (success) -> Void in
        println("SUCCESS!")
    }
    

    There is a separate signal errors in RACCommand which can be used to subscribe errors received from the execution signal (note: the errors are sent as next values):

    sendButtonItem.rac_command.errors.subscribeNext { (error) -> Void in
        println("ERROR!")
    }