Skip to content

Commit 3127ef4

Browse files
committed
Add modelSelected to the UIPickerView extension
1 parent b47f17b commit 3127ef4

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

RxCocoa/iOS/UIPickerView+Rx.swift

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,18 @@
5353
return RxPickerViewDelegateProxy.installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base)
5454
}
5555

56+
/**
57+
Reactive wrapper for `dataSource`.
58+
59+
For more information take a look at `DelegateProxyType` protocol documentation.
60+
*/
61+
public var dataSource: DelegateProxy {
62+
return RxPickerViewDataSourceProxy.proxyForObject(base)
63+
}
64+
65+
/**
66+
Reactive wrapper for `delegate` message `pickerView:didSelectRow:inComponent:`.
67+
*/
5668
public var itemSelected: ControlEvent<(Int, Int)> {
5769
let source = delegate
5870
.methodInvoked(#selector(UIPickerViewDelegate.pickerView(_:didSelectRow:inComponent:)))
@@ -62,6 +74,29 @@
6274
return ControlEvent(events: source)
6375
}
6476

77+
/**
78+
Reactive wrapper for `delegate` message `pickerView:didSelectRow:inComponent:`.
79+
80+
It can be only used when one of the `rx.itemTitles, rx.itemAttributedTitles, items(_ source: O)` methods is used to bind observable sequence,
81+
or any other data source conforming to a `ViewDataSourceType` protocol.
82+
83+
```
84+
pickerView.rx.modelSelected(MyModel.self)
85+
.map { ...
86+
```
87+
- parameter modelType: Type of a Model which bound to the dataSource
88+
*/
89+
public func modelSelected<T>(_ modelType: T.Type) -> ControlEvent<T> {
90+
let source = itemSelected.flatMap { [weak view = self.base as UIPickerView] (row, _) -> Observable<T> in
91+
guard let view = view else {
92+
return Observable.empty()
93+
}
94+
return Observable.just(try view.rx.model(at: row))
95+
}
96+
97+
return ControlEvent(events: source)
98+
}
99+
65100
/**
66101
Binds sequences of elements to picker view rows.
67102

@@ -191,6 +226,15 @@
191226
return Disposables.create(delegateSubscription, dataSourceSubscription)
192227
}
193228
}
229+
230+
/**
231+
Synchronous helper method for retrieving a model at indexPath through a reactive data source.
232+
*/
233+
public func model<T>(at index: Int) throws -> T {
234+
let dataSource: ViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.itemTitles, rx.itemAttributedTitles, items(_ source: O)` methods was used.")
235+
236+
return castOrFatalError(try dataSource.model(at: index))
237+
}
194238
}
195239

196240
#endif

0 commit comments

Comments
 (0)