Swift函数举例


Swift函数举例

========================
这里tate, Request, RequestID, Event都是泛型,函数的返回值为闭包(ObservableSchedulerContext<State>) -> Observable<Event>,闭包(State) -> [RequestID: Request]的返回值是一个字典

/**
 State: State type of the system.
 Request: Subset of state used to control the feedback loop.
 For every uniquely identifiable request `effects` closure is invoked with the initial value of the request and future requests corresponding to the same identifier.
 Subsequent equal values of request are not emitted from the effects state parameter.
 - parameter requests: Requests to perform some effects.
 - parameter effects: The request effects.
 - parameter initial: Initial request.
 - parameter state: Latest request state.
 - returns: The feedback loop performing the effects.
 */
public func react<State, Request: Equatable, RequestID, Event>(
    requests: @escaping (State) -> [RequestID: Request],
    effects: @escaping (_ initial: Request, _ state: Observable<Request>) -> Observable<Event>
) -> (ObservableSchedulerContext<State>) -> Observable<Event> {
    return { stateContext in
        Observable.create { observer in
            let state = RequestLifetimeTracking<Request, RequestID, Event>(
                effects: effects,
                scheduler: stateContext.scheduler,
                observer: observer
            )

            let subscription = stateContext.source
                .map(requests)
                .subscribe { event in
                    switch event {
                    case .next(let requests):
                        state.forwardRequests(requests)
                    case .error(let error):
                        observer.on(.error(error))
                    case .completed:
                        observer.on(.completed)
                    }
                }

            return Disposables.create {
                state.dispose()
                subscription.dispose()
            }
        }
    }
}

泛型WeakOwner继承AnyObject,这里where的条件限定函数的参数,与返回的闭包无关

/**
 Bi-directional binding of a system State to external state machine and events from it.
 Strongify owner.
 */
public func bind<State, Event, WeakOwner>(_ owner: WeakOwner, _ bindings: @escaping (WeakOwner, ObservableSchedulerContext<State>) -> (Bindings<Event>))
    -> (ObservableSchedulerContext<State>) -> Observable<Event> where WeakOwner: AnyObject {
    return bind(bindingsStrongify(owner, bindings))
}

文章作者: 张赛东
文章链接: https://zsd.name
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 张赛东 !
评论
  目录