-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
UITableView+Rx.swift
405 lines (332 loc) · 15.7 KB
/
UITableView+Rx.swift
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//
// UITableView+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 4/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import RxSwift
import UIKit
// Items
extension Reactive where Base: UITableView {
/**
Binds sequences of elements to table view rows.
- parameter source: Observable sequence of items.
- parameter cellFactory: Transform between sequence elements and view cells.
- returns: Disposable object that can be used to unbind.
Example:
let items = Observable.just([
"First Item",
"Second Item",
"Third Item"
])
items
.bind(to: tableView.rx.items) { (tableView, row, element) in
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = "\(element) @ row \(row)"
return cell
}
.disposed(by: disposeBag)
*/
public func items<Sequence: Swift.Sequence, Source: ObservableType>
(_ source: Source)
-> (_ cellFactory: @escaping (UITableView, Int, Sequence.Element) -> UITableViewCell)
-> Disposable
where Source.Element == Sequence {
return { cellFactory in
let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<Sequence>(cellFactory: cellFactory)
return self.items(dataSource: dataSource)(source)
}
}
/**
Binds sequences of elements to table view rows.
- parameter cellIdentifier: Identifier used to dequeue cells.
- parameter source: Observable sequence of items.
- parameter configureCell: Transform between sequence elements and view cells.
- parameter cellType: Type of table view cell.
- returns: Disposable object that can be used to unbind.
Example:
let items = Observable.just([
"First Item",
"Second Item",
"Third Item"
])
items
.bind(to: tableView.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { (row, element, cell) in
cell.textLabel?.text = "\(element) @ row \(row)"
}
.disposed(by: disposeBag)
*/
public func items<Sequence: Swift.Sequence, Cell: UITableViewCell, Source: ObservableType>
(cellIdentifier: String, cellType: Cell.Type = Cell.self)
-> (_ source: Source)
-> (_ configureCell: @escaping (Int, Sequence.Element, Cell) -> Void)
-> Disposable
where Source.Element == Sequence {
return { source in
return { configureCell in
let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<Sequence> { tv, i, item in
let indexPath = IndexPath(item: i, section: 0)
let cell = tv.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! Cell
configureCell(i, item, cell)
return cell
}
return self.items(dataSource: dataSource)(source)
}
}
}
/**
Binds sequences of elements to table view rows using a custom reactive data used to perform the transformation.
This method will retain the data source for as long as the subscription isn't disposed (result `Disposable`
being disposed).
In case `source` observable sequence terminates successfully, the data source will present latest element
until the subscription isn't disposed.
- parameter dataSource: Data source used to transform elements to view cells.
- parameter source: Observable sequence of items.
- returns: Disposable object that can be used to unbind.
*/
public func items<
DataSource: RxTableViewDataSourceType & UITableViewDataSource,
Source: ObservableType>
(dataSource: DataSource)
-> (_ source: Source)
-> Disposable
where DataSource.Element == Source.Element {
return { source in
// This is called for sideeffects only, and to make sure delegate proxy is in place when
// data source is being bound.
// This is needed because theoretically the data source subscription itself might
// call `self.rx.delegate`. If that happens, it might cause weird side effects since
// setting data source will set delegate, and UITableView might get into a weird state.
// Therefore it's better to set delegate proxy first, just to be sure.
_ = self.delegate
// Strong reference is needed because data source is in use until result subscription is disposed
return source.subscribeProxyDataSource(ofObject: self.base, dataSource: dataSource as UITableViewDataSource, retainDataSource: true) { [weak tableView = self.base] (_: RxTableViewDataSourceProxy, event) -> Void in
guard let tableView = tableView else {
return
}
dataSource.tableView(tableView, observedEvent: event)
}
}
}
}
extension Reactive where Base: UITableView {
/**
Reactive wrapper for `dataSource`.
For more information take a look at `DelegateProxyType` protocol documentation.
*/
public var dataSource: DelegateProxy<UITableView, UITableViewDataSource> {
return RxTableViewDataSourceProxy.proxy(for: base)
}
/**
Installs data source as forwarding delegate on `rx.dataSource`.
Data source won't be retained.
It enables using normal delegate mechanism with reactive delegate mechanism.
- parameter dataSource: Data source object.
- returns: Disposable object that can be used to unbind the data source.
*/
public func setDataSource(_ dataSource: UITableViewDataSource)
-> Disposable {
return RxTableViewDataSourceProxy.installForwardDelegate(dataSource, retainDelegate: false, onProxyForObject: self.base)
}
// events
/**
Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`.
*/
public var itemSelected: ControlEvent<IndexPath> {
let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didSelectRowAt:)))
.map { a in
return try castOrThrow(IndexPath.self, a[1])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`.
*/
public var itemDeselected: ControlEvent<IndexPath> {
let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didDeselectRowAt:)))
.map { a in
return try castOrThrow(IndexPath.self, a[1])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:accessoryButtonTappedForRowWithIndexPath:`.
*/
public var itemAccessoryButtonTapped: ControlEvent<IndexPath> {
let source: Observable<IndexPath> = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:accessoryButtonTappedForRowWith:)))
.map { a in
return try castOrThrow(IndexPath.self, a[1])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`.
*/
public var itemInserted: ControlEvent<IndexPath> {
let source = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:commit:forRowAt:)))
.filter { a in
return UITableViewCell.EditingStyle(rawValue: (try castOrThrow(NSNumber.self, a[1])).intValue) == .insert
}
.map { a in
return (try castOrThrow(IndexPath.self, a[2]))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`.
*/
public var itemDeleted: ControlEvent<IndexPath> {
let source = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:commit:forRowAt:)))
.filter { a in
return UITableViewCell.EditingStyle(rawValue: (try castOrThrow(NSNumber.self, a[1])).intValue) == .delete
}
.map { a in
return try castOrThrow(IndexPath.self, a[2])
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:moveRowAtIndexPath:toIndexPath:`.
*/
public var itemMoved: ControlEvent<ItemMovedEvent> {
let source: Observable<ItemMovedEvent> = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:moveRowAt:to:)))
.map { a in
return (try castOrThrow(IndexPath.self, a[1]), try castOrThrow(IndexPath.self, a[2]))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:willDisplayCell:forRowAtIndexPath:`.
*/
public var willDisplayCell: ControlEvent<WillDisplayCellEvent> {
let source: Observable<WillDisplayCellEvent> = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:willDisplay:forRowAt:)))
.map { a in
return (try castOrThrow(UITableViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2]))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didEndDisplayingCell:forRowAtIndexPath:`.
*/
public var didEndDisplayingCell: ControlEvent<DidEndDisplayingCellEvent> {
let source: Observable<DidEndDisplayingCellEvent> = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didEndDisplaying:forRowAt:)))
.map { a in
return (try castOrThrow(UITableViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2]))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`.
It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence,
or any other data source conforming to `SectionedViewDataSourceType` protocol.
```
tableView.rx.modelSelected(MyModel.self)
.map { ...
```
*/
public func modelSelected<T>(_ modelType: T.Type) -> ControlEvent<T> {
let source: Observable<T> = self.itemSelected.flatMap { [weak view = self.base as UITableView] indexPath -> Observable<T> in
guard let view = view else {
return Observable.empty()
}
return Observable.just(try view.rx.model(at: indexPath))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`.
It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence,
or any other data source conforming to `SectionedViewDataSourceType` protocol.
```
tableView.rx.modelDeselected(MyModel.self)
.map { ...
```
*/
public func modelDeselected<T>(_ modelType: T.Type) -> ControlEvent<T> {
let source: Observable<T> = self.itemDeselected.flatMap { [weak view = self.base as UITableView] indexPath -> Observable<T> in
guard let view = view else {
return Observable.empty()
}
return Observable.just(try view.rx.model(at: indexPath))
}
return ControlEvent(events: source)
}
/**
Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`.
It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence,
or any other data source conforming to `SectionedViewDataSourceType` protocol.
```
tableView.rx.modelDeleted(MyModel.self)
.map { ...
```
*/
public func modelDeleted<T>(_ modelType: T.Type) -> ControlEvent<T> {
let source: Observable<T> = self.itemDeleted.flatMap { [weak view = self.base as UITableView] indexPath -> Observable<T> in
guard let view = view else {
return Observable.empty()
}
return Observable.just(try view.rx.model(at: indexPath))
}
return ControlEvent(events: source)
}
/**
Synchronous helper method for retrieving a model at indexPath through a reactive data source.
*/
public func model<T>(at indexPath: IndexPath) throws -> T {
let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.items*` methods was used.")
let element = try dataSource.model(at: indexPath)
return castOrFatalError(element)
}
}
@available(iOS 10.0, tvOS 10.0, *)
extension Reactive where Base: UITableView {
/// Reactive wrapper for `prefetchDataSource`.
///
/// For more information take a look at `DelegateProxyType` protocol documentation.
public var prefetchDataSource: DelegateProxy<UITableView, UITableViewDataSourcePrefetching> {
return RxTableViewDataSourcePrefetchingProxy.proxy(for: base)
}
/**
Installs prefetch data source as forwarding delegate on `rx.prefetchDataSource`.
Prefetch data source won't be retained.
It enables using normal delegate mechanism with reactive delegate mechanism.
- parameter prefetchDataSource: Prefetch data source object.
- returns: Disposable object that can be used to unbind the data source.
*/
public func setPrefetchDataSource(_ prefetchDataSource: UITableViewDataSourcePrefetching)
-> Disposable {
return RxTableViewDataSourcePrefetchingProxy.installForwardDelegate(prefetchDataSource, retainDelegate: false, onProxyForObject: self.base)
}
/// Reactive wrapper for `prefetchDataSource` message `tableView(_:prefetchRowsAt:)`.
public var prefetchRows: ControlEvent<[IndexPath]> {
let source = RxTableViewDataSourcePrefetchingProxy.proxy(for: base).prefetchRowsPublishSubject
return ControlEvent(events: source)
}
/// Reactive wrapper for `prefetchDataSource` message `tableView(_:cancelPrefetchingForRowsAt:)`.
public var cancelPrefetchingForRows: ControlEvent<[IndexPath]> {
let source = prefetchDataSource.methodInvoked(#selector(UITableViewDataSourcePrefetching.tableView(_:cancelPrefetchingForRowsAt:)))
.map { a in
return try castOrThrow(Array<IndexPath>.self, a[1])
}
return ControlEvent(events: source)
}
}
#endif
#if os(tvOS)
extension Reactive where Base: UITableView {
/**
Reactive wrapper for `delegate` message `tableView:didUpdateFocusInContext:withAnimationCoordinator:`.
*/
public var didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UITableViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> {
let source = delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didUpdateFocusIn:with:)))
.map { a -> (context: UITableViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in
let context = try castOrThrow(UITableViewFocusUpdateContext.self, a[1])
let animationCoordinator = try castOrThrow(UIFocusAnimationCoordinator.self, a[2])
return (context: context, animationCoordinator: animationCoordinator)
}
return ControlEvent(events: source)
}
}
#endif