Swift函数举例

Swift函数举例

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
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的条件限定函数的参数,与返回的闭包无关

1
2
3
4
5
6
7
8
/**
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))
}