ReactiveCocoa 4设置启用/禁用操作

时间:2016-02-15 20:44:39

标签: swift reactive-cocoa-4

我正在使用ReactiveCocoa4为我的项目添加一些基本的登录功能。我已经设置了用户名'和密码'我的viewModel中的MutableProperties并将它们绑定到viewController中的关联textFields。到目前为止一直很好,但我仍然坚持设置Action以执行网络请求。本质上,我希望Action采用输入元组(用户名:字符串,密码:字符串)并输出我的自定义用户对象' SBUser'。我还对用户名和密码输入进行了一些基本验证,并将其与Action的启用状态联系起来。我的viewModel代码如下。

final class AuthenticationVM {

let client: Client
let authenticationType: AuthenticationType
let username = MutableProperty<String>("")
let password = MutableProperty<String>("")
let loginAction: Action<(username: String, password: String), SBUser, Error>

init(client: Client, authenticationType: AuthenticationType) {
    self.client = client
    self.authenticationType = authenticationType

    let validation = combineLatest(username.producer, password.producer)
            .map({ (username, password) -> Bool in
                return username.characters.count > 2 && password.characters.count > 2 })
            .skipRepeats()

    loginAction = Action<(username: String, password: String), SBUser, Error>(enabledIf: validation) { (username: String, password: String) in
        return SignalProducer<SBUser, Error> { [unowned self] observer, _ in
            self.client.request(API.logInWithUsername(username, password: password)) { response in
                        switch response.result {
                        case .Success(let user):
                            observer.sendNext(user)
                        case .Failure(let error):
                            observer.sendFailed(error)
                        }
            }
        }
    }
}

}

我收到错误,上下文关闭类型&#39; - &gt; SignalProducer&lt; ,_&gt;&#39;期望1个参数,但在闭包体中使用了2个。是不是可以将这样的元组传递给Action的输入?

2 个答案:

答案 0 :(得分:1)

loginAction = Action<(username: String, password: String), SBUser, Error>(enabledIf: MutableProperty(validation)) { (username: String, password: String) in
        return SignalProducer<SBUser, Error> { [unowned self] observer, _ in
            self.client.request(API.logInWithUsername(username, password: password)) { response in
                switch response.result {
                case .Success(let user):
                    observer.sendNext(user)
                case .Failure(let error):
                    observer.sendFailed(error)
                }
            }
        }
    }

对可变属性进行类型转换验证然后它将起作用enabledIf: MutableProperty(validation)

答案 1 :(得分:0)

public init<P : PropertyType where P.Value == Bool>(enabledIf: P, _ execute: Input -> ReactiveCocoa.SignalProducer<Output, Error>)

enabledIf必须是PropertyType。