Skip to content

Commit ed5f02e

Browse files
authored
Merge pull request #635 from Marcocanc/feature/observable-bindingtarget
Add binding operator to Signal.Observer
2 parents b1884a3 + 8707444 commit ed5f02e

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# master
22
*Please add new entries at the top.*
33
1. Fixed Result extensions ambiguity (#733, kudos to @nekrich)
4-
4+
1. Add `<~` binding operator to `Signal.Observer` (#635, kudos to @Marcocanc)
55

66
# 6.0.0
77
1. Dropped support for Swift 4.2 (Xcode 9)

Sources/UnidirectionalBinding.swift

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,33 @@ extension BindingTargetProvider {
102102
}
103103
}
104104

105+
extension Signal.Observer {
106+
/// Binds a source to a target, updating the target's value to the latest
107+
/// value sent by the source.
108+
///
109+
/// - note: Only `value` events will be forwarded to the Observer.
110+
/// The binding will automatically terminate when the target is
111+
/// deinitialized, or when the source sends a `completed` event.
112+
///
113+
/// - parameters:
114+
/// - target: A target to be bond to.
115+
/// - source: A source to bind.
116+
///
117+
/// - returns: A disposable that can be used to terminate binding before the
118+
/// deinitialization of the target or the source's `completed`
119+
/// event.
120+
@discardableResult
121+
public static func <~
122+
<Source: BindingSource>
123+
(observer: Signal<Value, Error>.Observer, source: Source) -> Disposable?
124+
where Source.Value == Value
125+
{
126+
return source.producer.startWithValues { [weak observer] in
127+
observer?.send(value: $0)
128+
}
129+
}
130+
}
131+
105132
/// A binding target that can be used with the `<~` operator.
106133
public struct BindingTarget<Value>: BindingTargetProvider {
107134
public let lifetime: Lifetime

Tests/ReactiveSwiftTests/UnidirectionalBindingSpec.swift

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,18 @@ class UnidirectionalBindingSpec: QuickSpec {
201201
expect(value).toEventually(equal(2))
202202
expect(mainQueueCounter.value).toEventually(equal(2))
203203
}
204+
205+
describe("observer binding operator") {
206+
it("should forward values to observer") {
207+
let targetPipe = Signal<Int?, Never>.pipe()
208+
let sourcePipe = Signal<Int?, Never>.pipe()
209+
let targetProperty = Property<Int?>(initial: nil, then: targetPipe.output)
210+
targetPipe.input <~ sourcePipe.output
211+
expect(targetProperty.value).to(beNil())
212+
sourcePipe.input.send(value: 1)
213+
expect(targetProperty.value).to(equal(1))
214+
}
215+
}
204216
}
205217
}
206218
}

0 commit comments

Comments
 (0)