0

尝试在我的项目中使用 ReativeSwift,但有些东西表现不佳,我检查了很多次,无法找出问题所在。一切都是正确的,只是没有调用。

class MSCreateScheduleViewModel: NSObject {

    var scheduleModel = MSScheduleModel()
    var validateAction: Action<(), Bool, NoError>!

    override init() {
        super.init()
        validateAction = Action(execute: { (_) -> SignalProducer<Bool, NoError> in
        return self.valiateScheduleModel()
    })
    validateAction.values.observeValues { (isok) in
        print("isok??") //this line not called
    }
    validateAction.values.observeCompleted {
        print("completed") //this line not called
    }
}

func valiateScheduleModel() -> SignalProducer<Bool, NoError> {
    let (signal, observer) = Signal<Bool, NoError>.pipe()
    let signalProducer = SignalProducer<Bool, NoError>(_ :signal)
    observer.send(value: true) //this line called
    observer.sendCompleted() //this line called
    return signalProducer
}
}
4

1 回答 1

0

SignalProducer当您像 in 一样通过包装现有信号来创建 a时valiateScheduleModel,生产者会在信号启动时观察信号并转发事件。这种情况下的问题是信号在生产者从函数返回并启动之前完成,因此不会转发任何事件。

如果您想创建一个true在启动时立即发送并完成的生产者,那么您应该执行以下操作:

func valiateScheduleModel() -> SignalProducer<Bool, NoError> {
    return SignalProducer<Bool, NoError> { observer, lifetime in
        observer.send(value: true)
        observer.sendCompleted()
    }
}

在生产者启动之前,不会执行闭包,因此Action会看到事件。

于 2019-08-11T15:06:54.630 回答