From 6757b8287262b14178d0fa6b2286fde01e495c17 Mon Sep 17 00:00:00 2001 From: Lee Sun-Hyoup Date: Thu, 7 Jul 2016 18:53:59 +0900 Subject: [PATCH 01/52] Remove typealias Parent line in Filter.swift --- RxSwift/Observables/Implementations/Filter.swift | 2 -- 1 file changed, 2 deletions(-) diff --git a/RxSwift/Observables/Implementations/Filter.swift b/RxSwift/Observables/Implementations/Filter.swift index b78fafb3..9adb0b28 100644 --- a/RxSwift/Observables/Implementations/Filter.swift +++ b/RxSwift/Observables/Implementations/Filter.swift @@ -12,8 +12,6 @@ class FilterSink: Sink, ObserverType { typealias Predicate = (Element) throws -> Bool typealias Element = O.E - typealias Parent = Filter - private let _predicate: Predicate init(predicate: Predicate, observer: O) { From 0c8d28b1b6bd739d24167fd4a7a09816357eef03 Mon Sep 17 00:00:00 2001 From: Krunoslav Zaher Date: Sat, 23 Jul 2016 16:20:10 +0200 Subject: [PATCH 02/52] Fixes disposing for debug operator in case of termination event. --- Rx.xcodeproj/project.pbxproj | 8 +++ .../Observables/Implementations/Debug.swift | 15 +++-- RxSwift/Observables/Observable+Debug.swift | 2 +- .../Tests/Observable+DebugTest.swift | 63 +++++++++++++++++++ 4 files changed, 81 insertions(+), 7 deletions(-) create mode 100644 Tests/RxSwiftTests/Tests/Observable+DebugTest.swift diff --git a/Rx.xcodeproj/project.pbxproj b/Rx.xcodeproj/project.pbxproj index 14db7eb6..bf8733d7 100644 --- a/Rx.xcodeproj/project.pbxproj +++ b/Rx.xcodeproj/project.pbxproj @@ -810,6 +810,9 @@ C8E7B36A1C30C6B800B34368 /* TestableObservable.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8E7B3681C30C6B800B34368 /* TestableObservable.swift */; }; C8E7B36B1C30C6B800B34368 /* TestableObservable.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8E7B3681C30C6B800B34368 /* TestableObservable.swift */; }; C8E7B36C1C30C6B800B34368 /* TestableObservable.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8E7B3681C30C6B800B34368 /* TestableObservable.swift */; }; + C8E9E42B1D43B26C0049644E /* Observable+DebugTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8E9E42A1D43B26C0049644E /* Observable+DebugTest.swift */; }; + C8E9E42C1D43B26C0049644E /* Observable+DebugTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8E9E42A1D43B26C0049644E /* Observable+DebugTest.swift */; }; + C8E9E42D1D43B26C0049644E /* Observable+DebugTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8E9E42A1D43B26C0049644E /* Observable+DebugTest.swift */; }; C8F0BF921BBBFB8B001B112F /* Observable+Creation.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8093C981B8A72BE0088E94D /* Observable+Creation.swift */; }; C8F0BF931BBBFB8B001B112F /* ConnectableObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8093C4D1B8A72BE0088E94D /* ConnectableObservableType.swift */; }; C8F0BF941BBBFB8B001B112F /* Just.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8C3DA021B9390C4004D233E /* Just.swift */; }; @@ -1740,6 +1743,7 @@ C8E3A7301C2606A900643FE6 /* Event+Equatable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Event+Equatable.swift"; sourceTree = ""; }; C8E3A7351C26088C00643FE6 /* Any+Equatable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Any+Equatable.swift"; sourceTree = ""; }; C8E7B3681C30C6B800B34368 /* TestableObservable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestableObservable.swift; sourceTree = ""; }; + C8E9E42A1D43B26C0049644E /* Observable+DebugTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Observable+DebugTest.swift"; sourceTree = ""; }; C8F0C0021BBBFB8B001B112F /* RxSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = RxSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; C8F0C04B1BBBFBB9001B112F /* RxCocoa.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = RxCocoa.framework; sourceTree = BUILT_PRODUCTS_DIR; }; C8F0C0581BBBFBCE001B112F /* RxBlocking.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = RxBlocking.framework; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -2379,6 +2383,7 @@ C835090C1C38706D0027C24C /* Observable+BlockingTest.swift */, C835090D1C38706D0027C24C /* Observable+ConcurrencyTest.swift */, C835090E1C38706D0027C24C /* Observable+CreationTest.swift */, + C8E9E42A1D43B26C0049644E /* Observable+DebugTest.swift */, C83509131C38706D0027C24C /* Observable+MultipleTest.swift */, C835090F1C38706D0027C24C /* Observable+MultipleTest+CombineLatest.swift */, C83509101C38706D0027C24C /* Observable+MultipleTest+CombineLatest.tt */, @@ -3556,6 +3561,7 @@ C83509531C38706E0027C24C /* Observable+AggregateTest.swift in Sources */, C8B290891C94D64600E923D0 /* RxTest+Controls.swift in Sources */, C83509291C38706E0027C24C /* PerformanceTools.swift in Sources */, + C8E9E42B1D43B26C0049644E /* Observable+DebugTest.swift in Sources */, C835096A1C38706E0027C24C /* TestErrors.swift in Sources */, 1AF67DA61CED430100C310FA /* ReplaySubjectTest.swift in Sources */, C83509561C38706E0027C24C /* Observable+ConcurrencyTest.swift in Sources */, @@ -3660,6 +3666,7 @@ C83509EC1C3875580027C24C /* MockDisposable.swift in Sources */, 1AF67DA31CED427D00C310FA /* PublishSubjectTest.swift in Sources */, C8350A111C38756A0027C24C /* Observable+SingleTest.swift in Sources */, + C8E9E42C1D43B26C0049644E /* Observable+DebugTest.swift in Sources */, C8350A2A1C3875B50027C24C /* RxMutableBox.swift in Sources */, C8350A151C38756A0027C24C /* ObserverTests.swift in Sources */, C83509B11C3874E20027C24C /* PerformanceTools.swift in Sources */, @@ -3729,6 +3736,7 @@ C8350A071C38755E0027C24C /* MainSchedulerTests.swift in Sources */, C83509B81C38750D0027C24C /* ControlEventTests.swift in Sources */, C83509CB1C3875230027C24C /* KVOObservableTests.swift in Sources */, + C8E9E42D1D43B26C0049644E /* Observable+DebugTest.swift in Sources */, C83509AD1C3874D70027C24C /* Foundation+Extensions.swift in Sources */, C83509C81C3875230027C24C /* DelegateProxyTest.swift in Sources */, C8350A0D1C38755E0027C24C /* Observable+MultipleTest+CombineLatest.swift in Sources */, diff --git a/RxSwift/Observables/Implementations/Debug.swift b/RxSwift/Observables/Implementations/Debug.swift index 4771a9a4..43dd83cd 100644 --- a/RxSwift/Observables/Implementations/Debug.swift +++ b/RxSwift/Observables/Implementations/Debug.swift @@ -14,9 +14,9 @@ func logEvent(_ identifier: String, dateFormat: DateFormatter, content: String) print("\(dateFormat.string(from: Date())): \(identifier) -> \(content)") } -class DebugSink : Sink, ObserverType { +class DebugSink : Sink, ObserverType { typealias Element = O.E - typealias Parent = Debug + typealias Parent = Debug private let _parent: Parent private let _timestampFormatter = DateFormatter() @@ -40,6 +40,9 @@ class DebugSink : Sink, ObserverType { logEvent(_parent._identifier, dateFormat: _timestampFormatter, content: "Event \(eventNormalized)") forwardOn(event) + if event.isStopEvent { + dispose() + } } override func dispose() { @@ -48,12 +51,12 @@ class DebugSink : Sink, ObserverType { } } -class Debug : Producer { +class Debug : Producer { private let _identifier: String - private let _source: Observable + private let _source: Source - init(source: Observable, identifier: String?, file: String, line: UInt, function: String) { + init(source: Source, identifier: String?, file: String, line: UInt, function: String) { if let identifier = identifier { _identifier = identifier } @@ -70,7 +73,7 @@ class Debug : Producer { _source = source } - override func run(_ observer: O) -> Disposable { + override func run(_ observer: O) -> Disposable { let sink = DebugSink(parent: self, observer: observer) sink.disposable = _source.subscribe(sink) return sink diff --git a/RxSwift/Observables/Observable+Debug.swift b/RxSwift/Observables/Observable+Debug.swift index 331940c5..c5799e09 100644 --- a/RxSwift/Observables/Observable+Debug.swift +++ b/RxSwift/Observables/Observable+Debug.swift @@ -23,6 +23,6 @@ extension ObservableType { // @warn_unused_result(message:"http://git.io/rxs.uo") public func debug(_ identifier: String? = nil, file: String = #file, line: UInt = #line, function: String = #function) -> Observable { - return Debug(source: self.asObservable(), identifier: identifier, file: file, line: line, function: function) + return Debug(source: self, identifier: identifier, file: file, line: line, function: function) } } diff --git a/Tests/RxSwiftTests/Tests/Observable+DebugTest.swift b/Tests/RxSwiftTests/Tests/Observable+DebugTest.swift new file mode 100644 index 00000000..d2f985dc --- /dev/null +++ b/Tests/RxSwiftTests/Tests/Observable+DebugTest.swift @@ -0,0 +1,63 @@ +// +// Observable+DebugTest.swift +// Rx +// +// Created by Krunoslav Zaher on 7/23/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Foundation +import XCTest +import RxSwift +import RxTests + +class ObservableDebugTest : RxTest { + +} + +// MARK: debug +extension ObservableDebugTest { + func testDebug_Completed() { + let scheduler = TestScheduler(initialClock: 0) + + let xs = scheduler.createHotObservable([ + next(210, 0), + completed(600) + ]) + + let res = scheduler.start { () -> Observable in + return xs.debug() + } + + XCTAssertEqual(res.events, [ + next(210, 0), + completed(600) + ]) + + XCTAssertEqual(xs.subscriptions, [ + Subscription(200, 600) + ]) + } + + func testDebug_Error() { + let scheduler = TestScheduler(initialClock: 0) + + let xs = scheduler.createHotObservable([ + next(210, 0), + error(600, testError) + ]) + + let res = scheduler.start { () -> Observable in + return xs.debug() + } + + XCTAssertEqual(res.events, [ + next(210, 0), + error(600, testError) + ]) + + XCTAssertEqual(xs.subscriptions, [ + Subscription(200, 600) + ]) + } +} From f303efb0779b86be814e8b80bc4ee9e5677db9bf Mon Sep 17 00:00:00 2001 From: Suyeol Jeon Date: Wed, 27 Jul 2016 04:15:17 +0900 Subject: [PATCH 03/52] Fix type mismatch in UITableView.rx_willDisplayCell --- RxCocoa/iOS/UITableView+Rx.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RxCocoa/iOS/UITableView+Rx.swift b/RxCocoa/iOS/UITableView+Rx.swift index 8b1472c1..d51621e5 100644 --- a/RxCocoa/iOS/UITableView+Rx.swift +++ b/RxCocoa/iOS/UITableView+Rx.swift @@ -214,7 +214,7 @@ extension UITableView { Reactive wrapper for `delegate` message `tableView:willDisplayCell:forRowAtIndexPath:`. */ public var rx_willDisplayCell: ControlEvent { - let source: Observable = rx_delegate.observe(#selector(UITableViewDelegate.tableView(_:willDisplayCell:forRowAtIndexPath:))) + let source: Observable = rx_delegate.observe(#selector(UITableViewDelegate.tableView(_:willDisplayCell:forRowAtIndexPath:))) .map { a in return (try castOrThrow(UITableViewCell.self, a[1]), try castOrThrow(NSIndexPath.self, a[2])) } From 40eb4520406ef05a42d634e550f3945c6888130e Mon Sep 17 00:00:00 2001 From: Raphael Silva Date: Thu, 28 Jul 2016 18:06:29 -0300 Subject: [PATCH 04/52] Update Contents.swift Typo fixed - it was missing the `ed` in called. --- .../Pages/Introduction.xcplaygroundpage/Contents.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Rx.playground/Pages/Introduction.xcplaygroundpage/Contents.swift b/Rx.playground/Pages/Introduction.xcplaygroundpage/Contents.swift index 36f2faa0..84776796 100644 --- a/Rx.playground/Pages/Introduction.xcplaygroundpage/Contents.swift +++ b/Rx.playground/Pages/Introduction.xcplaygroundpage/Contents.swift @@ -44,7 +44,7 @@ All of these various systems makes our code needlessly complex. Wouldn't it be b `--tap--tap----------tap--> // "|" = Continues indefinitely, such as a sequence of button taps` - > These diagrams are call marble diagrams. You can learn more about them at [RxMarbles.com](http://rxmarbles.com). + > These diagrams are called marble diagrams. You can learn more about them at [RxMarbles.com](http://rxmarbles.com). */ /*: ### Observables and observers (aka subscribers) From 544e00d917cd4c216ae15c34aeb2549d531a3f61 Mon Sep 17 00:00:00 2001 From: nishitani yuki Date: Mon, 1 Aug 2016 13:52:57 +0900 Subject: [PATCH 05/52] Fix minor typo --- Documentation/Schedulers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/Schedulers.md b/Documentation/Schedulers.md index 6dbe7cc3..331f5e39 100644 --- a/Documentation/Schedulers.md +++ b/Documentation/Schedulers.md @@ -13,7 +13,7 @@ There are two main operators that work with schedulers, `observeOn` and `subscri If you want to perform work on a different scheduler just use `observeOn(scheduler)` operator. -You would usually use `observeOn` a lot more often then `subscribeOn`. +You would usually use `observeOn` a lot more often than `subscribeOn`. In case `observeOn` isn't explicitly specified, work will be performed on whichever thread/scheduler elements are generated. From dffd6f0e1cca0b8bb196cb54909b82686b30b7e2 Mon Sep 17 00:00:00 2001 From: Krunoslav Zaher Date: Mon, 1 Aug 2016 10:18:11 +0200 Subject: [PATCH 06/52] Moves playgrounds from workspace to project. #806 --- Rx.xcodeproj/project.pbxproj | 2 ++ Rx.xcworkspace/contents.xcworkspacedata | 3 --- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/Rx.xcodeproj/project.pbxproj b/Rx.xcodeproj/project.pbxproj index 3ba598d0..701b707f 100644 --- a/Rx.xcodeproj/project.pbxproj +++ b/Rx.xcodeproj/project.pbxproj @@ -1715,6 +1715,7 @@ C8C4B4C01C17727000828BD5 /* MessageSentObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MessageSentObserver.swift; sourceTree = ""; }; C8D132431C42D15E00B59FFF /* SectionedViewDataSourceType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SectionedViewDataSourceType.swift; sourceTree = ""; }; C8D132521C42DA7F00B59FFF /* SectionedViewDataSourceMock.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SectionedViewDataSourceMock.swift; sourceTree = ""; }; + C8D2C1501D4F3CD6006E2431 /* Rx.playground */ = {isa = PBXFileReference; lastKnownFileType = file.playground; path = Rx.playground; sourceTree = ""; }; C8DB967D1BF7496C0084BD53 /* KVORepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = KVORepresentable.swift; sourceTree = ""; }; C8DB96821BF754C80084BD53 /* NSObject+Rx+KVORepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "NSObject+Rx+KVORepresentable.swift"; sourceTree = ""; }; C8DB96871BF756F40084BD53 /* KVORepresentable+CoreGraphics.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "KVORepresentable+CoreGraphics.swift"; sourceTree = ""; }; @@ -2513,6 +2514,7 @@ C8A56ACD1AD7424700B4673B = { isa = PBXGroup; children = ( + C8D2C1501D4F3CD6006E2431 /* Rx.playground */, C8093C471B8A72BE0088E94D /* RxSwift */, C8093F571B8A73A20088E94D /* RxBlocking */, C8093E801B8A732E0088E94D /* RxCocoa */, diff --git a/Rx.xcworkspace/contents.xcworkspacedata b/Rx.xcworkspace/contents.xcworkspacedata index f08b0831..1d0c2b1b 100644 --- a/Rx.xcworkspace/contents.xcworkspacedata +++ b/Rx.xcworkspace/contents.xcworkspacedata @@ -128,9 +128,6 @@ location = "group:Warnings.md"> - - From 7f84ec604e7cff89b9b1f5eca803098d9a8d1e57 Mon Sep 17 00:00:00 2001 From: Yuki Nagai Date: Tue, 2 Aug 2016 15:46:11 +0900 Subject: [PATCH 07/52] WIP. Update for Xcode 8 beta 4. --- Documentation/GettingStarted.md | 4 ++-- Documentation/Linux.md | 2 +- Rx.playground/Sources/SupportCode.swift | 4 ++-- RxBlocking/BlockingObservable+Operators.swift | 8 +++---- .../CocoaUnits/Driver/Driver+Operators.swift | 2 +- .../ObservableConvertibleType+Driver.swift | 2 +- RxCocoa/Common/Observables/NSObject+Rx.swift | 12 ++++++++-- .../Common/Observables/NSURLSession+Rx.swift | 4 ++-- RxCocoa/Common/RxCocoa.swift | 22 +++++++++---------- RxCocoa/iOS/UICollectionView+Rx.swift | 2 +- RxCocoa/iOS/UILabel+Rx.swift | 2 +- RxCocoa/iOS/UITableView+Rx.swift | 2 +- .../DataSources/DataSources.swift | 4 ++-- .../DataSources/Differentiator.swift | 2 +- .../TestScheduler+MarbleTests.swift | 6 ++--- .../Services/ActivityIndicator.swift | 2 +- .../RxExample/Services/Reachability.swift | 2 +- RxSwift/Concurrency/Lock.swift | 4 ++-- RxSwift/Concurrency/LockOwnerType.swift | 2 +- RxSwift/Errors.swift | 2 +- RxSwift/Event.swift | 4 ++-- RxSwift/Observable+Extensions.swift | 4 ++-- RxSwift/Observables/Implementations/Amb.swift | 2 +- .../Observables/Implementations/Buffer.swift | 2 +- .../Observables/Implementations/Catch.swift | 4 ++-- .../CombineLatest+CollectionType.swift | 2 +- .../Implementations/CombineLatest.swift | 10 ++++----- .../ConnectableObservable.swift | 6 ++--- .../Observables/Implementations/Error.swift | 4 ++-- .../Observables/Implementations/Merge.swift | 6 ++--- .../Implementations/RefCount.swift | 2 +- .../Implementations/RetryWhen.swift | 4 ++-- .../Observables/Implementations/Sample.swift | 4 ++-- .../Implementations/ShareReplay1.swift | 2 +- .../ShareReplay1WhileConnected.swift | 2 +- .../Implementations/SingleAsync.swift | 2 +- .../Implementations/SkipUntil.swift | 4 ++-- .../Observables/Implementations/Switch.swift | 4 ++-- .../Observables/Implementations/Take.swift | 2 +- .../Implementations/TakeUntil.swift | 4 ++-- .../Implementations/Throttle.swift | 2 +- .../Observables/Implementations/Timeout.swift | 2 +- .../Observables/Implementations/Window.swift | 4 ++-- .../Implementations/WithLatestFrom.swift | 4 ++-- .../Implementations/Zip+CollectionType.swift | 2 +- RxSwift/Observables/Implementations/Zip.swift | 10 ++++----- RxSwift/Observables/Observable+Creation.swift | 2 +- RxSwift/Observables/Observable+Multiple.swift | 2 +- RxSwift/Observables/Observable+Single.swift | 8 +++---- RxSwift/ObserverType.swift | 6 ++--- RxSwift/Platform/Platform.Darwin.swift | 5 +++-- RxSwift/Platform/Platform.Linux.swift | 2 +- .../ConcurrentDispatchQueueScheduler.swift | 5 +++-- .../DispatchQueueSchedulerQOS.swift | 12 +++++----- .../Internal/DispatchQueueConfiguration.swift | 4 ++-- RxSwift/Schedulers/RecursiveScheduler.swift | 2 +- .../SerialDispatchQueueScheduler.swift | 8 +++---- RxSwift/Subjects/BehaviorSubject.swift | 2 +- RxSwift/Subjects/PublishSubject.swift | 2 +- RxSwift/Subjects/ReplaySubject.swift | 2 +- RxTests/XCTest+Rx.swift | 2 +- Tests/RxCocoaTests/KVOObservableTests.swift | 4 ++-- .../Mocks/PrimitiveHotObservable.swift | 2 +- .../Tests/Observable+SingleTest.swift | 6 ++--- .../Tests/Observable+SubscriptionTest.swift | 8 +++---- Tests/RxSwiftTests/Tests/ObserverTests.swift | 2 +- Tests/Tests/Recorded+Timeless.swift | 2 +- Tests/Tests/XCTest+AllTests.swift | 2 +- 68 files changed, 144 insertions(+), 134 deletions(-) diff --git a/Documentation/GettingStarted.md b/Documentation/GettingStarted.md index 83fe322d..d74befc7 100644 --- a/Documentation/GettingStarted.md +++ b/Documentation/GettingStarted.md @@ -79,7 +79,7 @@ Sequences in Rx are described by a push interface (aka callback). ```swift enum Event { case Next(Element) // next element of a sequence - case Error(ErrorProtocol) // sequence failed with error + case Error(Swift.Error) // sequence failed with error case Completed // sequence terminated successfully } @@ -102,7 +102,7 @@ If a sequence does not terminate in some way, resources will be allocated perman **Using dispose bags or `takeUntil` operator is a robust way of making sure resources are cleaned up. We recommend using them in production even if the sequences will terminate in finite time.** -In case you are curious why `ErrorProtocol` isn't generic, you can find explanation [here](DesignRationale.md#why-error-type-isnt-generic). +In case you are curious why `Swift.Error` isn't generic, you can find explanation [here](DesignRationale.md#why-error-type-isnt-generic). ## Disposing diff --git a/Documentation/Linux.md b/Documentation/Linux.md index 413b0ea1..1fd2d6e6 100644 --- a/Documentation/Linux.md +++ b/Documentation/Linux.md @@ -28,4 +28,4 @@ What works: What doesn't work: * Schedulers - because they are dependent on https://github.com/apple/swift-corelibs-libdispatch and it still hasn't been released * Multithreading - still no access to c11 locks -* For some reason it looks like Swift compiler generates wrong code when using `ErrorProtocol` on `Linux`, so don't use errors, otherwise you can get weird crashes. +* For some reason it looks like Swift compiler generates wrong code when using `Swift.Error` on `Linux`, so don't use errors, otherwise you can get weird crashes. diff --git a/Rx.playground/Sources/SupportCode.swift b/Rx.playground/Sources/SupportCode.swift index 7c653a7b..298f20e7 100644 --- a/Rx.playground/Sources/SupportCode.swift +++ b/Rx.playground/Sources/SupportCode.swift @@ -14,7 +14,7 @@ public func printExampleHeader(description: String) { print("\n--- \(description) example ---") } -public enum Error: ErrorProtocol { +public enum Error: Swift.Error { case test } @@ -27,7 +27,7 @@ public enum Error: ErrorProtocol { public func delay(delay: Double, closure: (Void) -> Void) { let delayTime = DispatchTime.now() + DispatchTimeInterval.seconds(Int(delay)) - DispatchQueue.main.after(when: delayTime) { + DispatchQueue.main.asyncAfter(deadline: delayTime) { closure() } } diff --git a/RxBlocking/BlockingObservable+Operators.swift b/RxBlocking/BlockingObservable+Operators.swift index faf5f025..783feeb9 100644 --- a/RxBlocking/BlockingObservable+Operators.swift +++ b/RxBlocking/BlockingObservable+Operators.swift @@ -22,7 +22,7 @@ extension BlockingObservable { public func toArray() throws -> [E] { var elements: [E] = Array() - var error: ErrorProtocol? + var error: Swift.Error? let lock = RunLoopLock() @@ -70,7 +70,7 @@ extension BlockingObservable { public func first() throws -> E? { var element: E? - var error: ErrorProtocol? + var error: Swift.Error? let d = SingleAssignmentDisposable() @@ -122,7 +122,7 @@ extension BlockingObservable { public func last() throws -> E? { var element: E? - var error: ErrorProtocol? + var error: Swift.Error? let d = SingleAssignmentDisposable() @@ -183,7 +183,7 @@ extension BlockingObservable { public func single(_ predicate: (E) throws -> Bool) throws -> E? { var element: E? - var error: ErrorProtocol? + var error: Swift.Error? let d = SingleAssignmentDisposable() diff --git a/RxCocoa/Common/CocoaUnits/Driver/Driver+Operators.swift b/RxCocoa/Common/CocoaUnits/Driver/Driver+Operators.swift index ea428d94..7c7e9ddb 100644 --- a/RxCocoa/Common/CocoaUnits/Driver/Driver+Operators.swift +++ b/RxCocoa/Common/CocoaUnits/Driver/Driver+Operators.swift @@ -137,7 +137,7 @@ extension DriverConvertibleType { - returns: The source sequence with the side-effecting behavior applied. */ // @warn_unused_result(message:"http://git.io/rxs.uo") - public func doOn(onNext: ((E) -> Void)? = nil, onError: ((ErrorProtocol) -> Void)? = nil, onCompleted: (() -> Void)? = nil) + public func doOn(onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil) -> Driver { let source = self.asObservable() .doOn(onNext: onNext, onError: onError, onCompleted: onCompleted) diff --git a/RxCocoa/Common/CocoaUnits/Driver/ObservableConvertibleType+Driver.swift b/RxCocoa/Common/CocoaUnits/Driver/ObservableConvertibleType+Driver.swift index 4ccfc56e..455bdff1 100644 --- a/RxCocoa/Common/CocoaUnits/Driver/ObservableConvertibleType+Driver.swift +++ b/RxCocoa/Common/CocoaUnits/Driver/ObservableConvertibleType+Driver.swift @@ -51,7 +51,7 @@ extension ObservableConvertibleType { - returns: Driving observable sequence. */ // @warn_unused_result(message:"http://git.io/rxs.uo") - public func asDriver(onErrorRecover: (error: ErrorProtocol) -> Driver) -> Driver { + public func asDriver(onErrorRecover: (error: Swift.Error) -> Driver) -> Driver { let source = self .asObservable() .observeOn(driverObserveOnScheduler) diff --git a/RxCocoa/Common/Observables/NSObject+Rx.swift b/RxCocoa/Common/Observables/NSObject+Rx.swift index 3539aa3b..fcaff000 100644 --- a/RxCocoa/Common/Observables/NSObject+Rx.swift +++ b/RxCocoa/Common/Observables/NSObject+Rx.swift @@ -126,6 +126,10 @@ extension NSObject { - returns: Observable sequence of object deallocating events. */ public func rx_sentMessage(_ selector: Selector) -> Observable<[AnyObject]> { + return Observable.create { _ in + return AnonymousDisposable {} + } + /* return rx_synchronized { // in case of dealloc selector replay subject behavior needs to be used if selector == deallocSelector { @@ -160,7 +164,7 @@ extension NSObject { subject.targetImplementation = targetImplementation return subject.asObservable() - } + }*/ } /** @@ -174,6 +178,10 @@ extension NSObject { - returns: Observable sequence of object deallocating events. */ public var rx_deallocating: Observable<()> { + return Observable.create { _ in + return AnonymousDisposable {} + } + /* return rx_synchronized { let subject: DeallocatingObservable @@ -202,7 +210,7 @@ extension NSObject { subject.targetImplementation = targetImplementation! return subject.asObservable() - } + }*/ } #endif } diff --git a/RxCocoa/Common/Observables/NSURLSession+Rx.swift b/RxCocoa/Common/Observables/NSURLSession+Rx.swift index e0d329ab..0e183bda 100644 --- a/RxCocoa/Common/Observables/NSURLSession+Rx.swift +++ b/RxCocoa/Common/Observables/NSURLSession+Rx.swift @@ -15,7 +15,7 @@ import RxSwift RxCocoa URL errors. */ public enum RxCocoaURLError - : ErrorProtocol + : Swift.Error , CustomDebugStringConvertible { /** Unknown error occurred. @@ -32,7 +32,7 @@ public enum RxCocoaURLError /** Deserialization error. */ - case deserializationError(error: ErrorProtocol) + case deserializationError(error: Swift.Error) } public extension RxCocoaURLError { diff --git a/RxCocoa/Common/RxCocoa.swift b/RxCocoa/Common/RxCocoa.swift index 1c1de971..5aba2e45 100644 --- a/RxCocoa/Common/RxCocoa.swift +++ b/RxCocoa/Common/RxCocoa.swift @@ -18,7 +18,7 @@ import RxSwift RxCocoa errors. */ public enum RxCocoaError - : ErrorProtocol + : Swift.Error , CustomDebugStringConvertible { /** Unknown error has occurred. @@ -69,7 +69,7 @@ public enum RxCocoaInterceptionMechanism { RxCocoa ObjC runtime modification errors. */ public enum RxCocoaObjCRuntimeError - : ErrorProtocol + : Swift.Error , CustomDebugStringConvertible { /** Unknown error has occurred. @@ -193,23 +193,23 @@ public extension RxCocoaObjCRuntimeError { switch self { case let .unknown(target): return "Unknown error occurred.\nTarget: `\(target)`" - case let objectMessagesAlreadyBeingIntercepted(target, interceptionMechanism): + case let .objectMessagesAlreadyBeingIntercepted(target, interceptionMechanism): let interceptionMechanismDescription = interceptionMechanism == .kvo ? "KVO" : "other interception mechanism" return "Collision between RxCocoa interception mechanism and \(interceptionMechanismDescription)." + " To resolve this conflict please use this interception mechanism first.\nTarget: \(target)" - case let selectorNotImplemented(target): + case let .selectorNotImplemented(target): return "Trying to observe messages for selector that isn't implemented.\nTarget: \(target)" - case let cantInterceptCoreFoundationTollFreeBridgedObjects(target): + case let .cantInterceptCoreFoundationTollFreeBridgedObjects(target): return "Interception of messages sent to Core Foundation isn't supported.\nTarget: \(target)" - case let threadingCollisionWithOtherInterceptionMechanism(target): + case let .threadingCollisionWithOtherInterceptionMechanism(target): return "Detected a conflict while modifying ObjC runtime.\nTarget: \(target)" - case let savingOriginalForwardingMethodFailed(target): + case let .savingOriginalForwardingMethodFailed(target): return "Saving original method implementation failed.\nTarget: \(target)" - case let replacingMethodWithForwardingImplementation(target): + case let .replacingMethodWithForwardingImplementation(target): return "Intercepting a sent message by replacing a method implementation with `_objc_msgForward` failed for some reason.\nTarget: \(target)" - case let observingPerformanceSensitiveMessages(target): + case let .observingPerformanceSensitiveMessages(target): return "Attempt to intercept one of the performance sensitive methods. \nTarget: \(target)" - case let observingMessagesWithUnsupportedReturnType(target): + case let .observingMessagesWithUnsupportedReturnType(target): return "Attempt to intercept a method with unsupported return type. \nTarget: \(target)" } } @@ -219,7 +219,7 @@ public extension RxCocoaObjCRuntimeError { // MARK: Error binding policies -func bindingErrorToInterface(_ error: ErrorProtocol) { +func bindingErrorToInterface(_ error: Swift.Error) { let error = "Binding error to UI: \(error)" #if DEBUG rxFatalError(error) diff --git a/RxCocoa/iOS/UICollectionView+Rx.swift b/RxCocoa/iOS/UICollectionView+Rx.swift index 685724b1..1fd54628 100644 --- a/RxCocoa/iOS/UICollectionView+Rx.swift +++ b/RxCocoa/iOS/UICollectionView+Rx.swift @@ -135,7 +135,7 @@ extension UICollectionView { .addDisposableTo(disposeBag) */ public func rx_itemsWithDataSource< - DataSource: protocol, + DataSource: RxCollectionViewDataSourceType & UICollectionViewDataSource, O: ObservableType where DataSource.Element == O.E > (_ dataSource: DataSource) diff --git a/RxCocoa/iOS/UILabel+Rx.swift b/RxCocoa/iOS/UILabel+Rx.swift index f7dfded9..ee3d8004 100644 --- a/RxCocoa/iOS/UILabel+Rx.swift +++ b/RxCocoa/iOS/UILabel+Rx.swift @@ -28,7 +28,7 @@ extension UILabel { /** Bindable sink for `attributedText` property. */ - public var rx_attributedText: AnyObserver { + public var rx_attributedText: AnyObserver { return UIBindingObserver(UIElement: self) { label, text in label.attributedText = text }.asObserver() diff --git a/RxCocoa/iOS/UITableView+Rx.swift b/RxCocoa/iOS/UITableView+Rx.swift index 4996d5b9..0eea50e5 100644 --- a/RxCocoa/iOS/UITableView+Rx.swift +++ b/RxCocoa/iOS/UITableView+Rx.swift @@ -138,7 +138,7 @@ extension UITableView { .addDisposableTo(disposeBag) */ public func rx_itemsWithDataSource< - DataSource: protocol, + DataSource: RxTableViewDataSourceType & UITableViewDataSource, O: ObservableType where DataSource.Element == O.E > (_ dataSource: DataSource) diff --git a/RxExample/RxDataSources/DataSources/DataSources.swift b/RxExample/RxDataSources/DataSources/DataSources.swift index 4a39cf9a..0d560711 100644 --- a/RxExample/RxDataSources/DataSources/DataSources.swift +++ b/RxExample/RxDataSources/DataSources/DataSources.swift @@ -8,7 +8,7 @@ import Foundation -enum RxDataSourceError : ErrorProtocol { +enum RxDataSourceError : Swift.Error { case unwrappingOptional case preconditionFailed(message: String) } @@ -22,7 +22,7 @@ func rxPrecondition(_ condition: Bool, _ message: @autoclosure() -> String) thro throw RxDataSourceError.preconditionFailed(message: message()) } -func rxDebugFatalError(_ error: ErrorProtocol) { +func rxDebugFatalError(_ error: Swift.Error) { rxDebugFatalError("\(error)") } diff --git a/RxExample/RxDataSources/DataSources/Differentiator.swift b/RxExample/RxDataSources/DataSources/Differentiator.swift index e9979e79..e3077b8a 100644 --- a/RxExample/RxDataSources/DataSources/Differentiator.swift +++ b/RxExample/RxDataSources/DataSources/Differentiator.swift @@ -9,7 +9,7 @@ import Foundation public enum DifferentiatorError - : ErrorProtocol + : Swift.Error , CustomDebugStringConvertible { case duplicateItem(item: Any) case duplicateSection(section: Any) diff --git a/RxExample/RxExample-iOSTests/TestScheduler+MarbleTests.swift b/RxExample/RxExample-iOSTests/TestScheduler+MarbleTests.swift index b749c17d..5cd2e991 100644 --- a/RxExample/RxExample-iOSTests/TestScheduler+MarbleTests.swift +++ b/RxExample/RxExample-iOSTests/TestScheduler+MarbleTests.swift @@ -41,7 +41,7 @@ extension TestScheduler { - `|` marks sequence completed */ - func parseEventsAndTimes(timeline: String, values: [String: T], errors: [String: ErrorProtocol] = [:]) -> [[Recorded>]] { + func parseEventsAndTimes(timeline: String, values: [String: T], errors: [String: Swift.Error] = [:]) -> [[Recorded>]] { //print("parsing: \(timeline)") typealias RecordedEvent = Recorded> @@ -112,7 +112,7 @@ extension TestScheduler { - returns: Observable sequence specified by timeline and values. */ - func createObservable(timeline: String, values: [String: T], errors: [String: ErrorProtocol] = [:]) -> Observable { + func createObservable(timeline: String, values: [String: T], errors: [String: Swift.Error] = [:]) -> Observable { let events = self.parseEventsAndTimes(timeline: timeline, values: values, errors: errors) return createObservable(events) } @@ -174,7 +174,7 @@ extension TestScheduler { - returns: Implementation of method that accepts arguments with parameter `Arg` and returns observable sequence with parameter `Ret`. */ - func mock(values: [String: Ret], errors: [String: ErrorProtocol] = [:], timelineSelector: (Arg) -> String) -> (Arg) -> Observable { + func mock(values: [String: Ret], errors: [String: Swift.Error] = [:], timelineSelector: (Arg) -> String) -> (Arg) -> Observable { return { (parameters: Arg) -> Observable in let timeline = timelineSelector(parameters) diff --git a/RxExample/RxExample/Services/ActivityIndicator.swift b/RxExample/RxExample/Services/ActivityIndicator.swift index 853afe6a..5ea8062b 100644 --- a/RxExample/RxExample/Services/ActivityIndicator.swift +++ b/RxExample/RxExample/Services/ActivityIndicator.swift @@ -39,7 +39,7 @@ When all activities complete `false` will be sent. public class ActivityIndicator : DriverConvertibleType { public typealias E = Bool - private let _lock = RecursiveLock() + private let _lock = NSRecursiveLock() private let _variable = Variable(0) private let _loading: Driver diff --git a/RxExample/RxExample/Services/Reachability.swift b/RxExample/RxExample/Services/Reachability.swift index a5f90440..ea000464 100644 --- a/RxExample/RxExample/Services/Reachability.swift +++ b/RxExample/RxExample/Services/Reachability.swift @@ -28,7 +28,7 @@ POSSIBILITY OF SUCH DAMAGE. import SystemConfiguration import Foundation -enum ReachabilityError: ErrorProtocol { +enum ReachabilityError: Swift.Error { case failedToCreateWithAddress(sockaddr_in) case failedToCreateWithHostname(String) case unableToSetCallback diff --git a/RxSwift/Concurrency/Lock.swift b/RxSwift/Concurrency/Lock.swift index a330c5fe..ca6f3202 100644 --- a/RxSwift/Concurrency/Lock.swift +++ b/RxSwift/Concurrency/Lock.swift @@ -59,10 +59,10 @@ protocol Lock { #else // https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000321.html - typealias SpinLock = RecursiveLock + typealias SpinLock = NSRecursiveLock #endif -extension RecursiveLock : Lock { +extension NSRecursiveLock : Lock { func performLocked( _ action: @noescape() -> Void) { lock(); defer { unlock() } action() diff --git a/RxSwift/Concurrency/LockOwnerType.swift b/RxSwift/Concurrency/LockOwnerType.swift index 0b50d8a7..fe61d72f 100644 --- a/RxSwift/Concurrency/LockOwnerType.swift +++ b/RxSwift/Concurrency/LockOwnerType.swift @@ -9,7 +9,7 @@ import Foundation protocol LockOwnerType : class, Lock { - var _lock: RecursiveLock { get } + var _lock: NSRecursiveLock { get } } extension LockOwnerType { diff --git a/RxSwift/Errors.swift b/RxSwift/Errors.swift index 237d6a5a..8074e161 100644 --- a/RxSwift/Errors.swift +++ b/RxSwift/Errors.swift @@ -15,7 +15,7 @@ let RxCompositeFailures = "RxCompositeFailures" Generic Rx error codes. */ public enum RxError - : ErrorProtocol + : Swift.Error , CustomDebugStringConvertible { /** Unknown error occured. diff --git a/RxSwift/Event.swift b/RxSwift/Event.swift index 1c8c6d0d..1852a091 100644 --- a/RxSwift/Event.swift +++ b/RxSwift/Event.swift @@ -19,7 +19,7 @@ public enum Event { case next(Element) /// Sequence terminated with an error. - case error(ErrorProtocol) + case error(Swift.Error) /// Sequence completed successfully. case completed @@ -57,7 +57,7 @@ extension Event { } /// - returns: If `Error` event, returns error. - public var error: ErrorProtocol? { + public var error: Swift.Error? { if case .error(let error) = self { return error } diff --git a/RxSwift/Observable+Extensions.swift b/RxSwift/Observable+Extensions.swift index 09dfe602..fec544a1 100644 --- a/RxSwift/Observable+Extensions.swift +++ b/RxSwift/Observable+Extensions.swift @@ -35,7 +35,7 @@ extension ObservableType { - returns: Subscription object used to unsubscribe from the observable sequence. */ // @warn_unused_result(message: "http://git.io/rxs.ud") - public func subscribe(onNext: ((E) -> Void)? = nil, onError: ((ErrorProtocol) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) + public func subscribe(onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable { let disposable: Disposable @@ -89,7 +89,7 @@ extension ObservableType { - returns: Subscription object used to unsubscribe from the observable sequence. */ // @warn_unused_result(message: "http://git.io/rxs.ud") - public func subscribeError(_ onError: (ErrorProtocol) -> Void) + public func subscribeError(_ onError: (Swift.Error) -> Void) -> Disposable { let observer = AnonymousObserver { e in if case .error(let error) = e { diff --git a/RxSwift/Observables/Implementations/Amb.swift b/RxSwift/Observables/Implementations/Amb.swift index bd536b3a..9ea6d8d3 100644 --- a/RxSwift/Observables/Implementations/Amb.swift +++ b/RxSwift/Observables/Implementations/Amb.swift @@ -54,7 +54,7 @@ class AmbSink : Sink { private let _parent: Parent - private let _lock = RecursiveLock() + private let _lock = NSRecursiveLock() // state private var _choice = AmbState.neither diff --git a/RxSwift/Observables/Implementations/Buffer.swift b/RxSwift/Observables/Implementations/Buffer.swift index c858ede1..823a4bcb 100644 --- a/RxSwift/Observables/Implementations/Buffer.swift +++ b/RxSwift/Observables/Implementations/Buffer.swift @@ -39,7 +39,7 @@ class BufferTimeCountSink private let _parent: Parent - let _lock = RecursiveLock() + let _lock = NSRecursiveLock() // state private let _timerD = SerialDisposable() diff --git a/RxSwift/Observables/Implementations/Catch.swift b/RxSwift/Observables/Implementations/Catch.swift index 02b7d5e7..baaeb000 100644 --- a/RxSwift/Observables/Implementations/Catch.swift +++ b/RxSwift/Observables/Implementations/Catch.swift @@ -76,7 +76,7 @@ class CatchSink : Sink, ObserverType { } class Catch : Producer { - typealias Handler = (ErrorProtocol) throws -> Observable + typealias Handler = (Swift.Error) throws -> Observable private let _source: Observable private let _handler: Handler @@ -101,7 +101,7 @@ class CatchSequenceSink - private var _lastError: ErrorProtocol? + private var _lastError: Swift.Error? override init(observer: O) { super.init(observer: observer) diff --git a/RxSwift/Observables/Implementations/CombineLatest+CollectionType.swift b/RxSwift/Observables/Implementations/CombineLatest+CollectionType.swift index 754c52c0..fb5754ce 100644 --- a/RxSwift/Observables/Implementations/CombineLatest+CollectionType.swift +++ b/RxSwift/Observables/Implementations/CombineLatest+CollectionType.swift @@ -15,7 +15,7 @@ class CombineLatestCollectionTypeSink , CombineLatestProtocol { typealias Element = O.E - let _lock = RecursiveLock() + let _lock = NSRecursiveLock() private let _arity: Int private var _numberOfValues = 0 @@ -72,7 +72,7 @@ class CombineLatestSink } } - func fail(_ error: ErrorProtocol) { + func fail(_ error: Swift.Error) { forwardOn(.error(error)) dispose() } @@ -101,12 +101,12 @@ class CombineLatestObserver private let _parent: CombineLatestProtocol - let _lock: RecursiveLock + let _lock: NSRecursiveLock private let _index: Int private let _this: Disposable private let _setLatestValue: ValueSetter - init(lock: RecursiveLock, parent: CombineLatestProtocol, index: Int, setLatestValue: ValueSetter, this: Disposable) { + init(lock: NSRecursiveLock, parent: CombineLatestProtocol, index: Int, setLatestValue: ValueSetter, this: Disposable) { _lock = lock _parent = parent _index = index diff --git a/RxSwift/Observables/Implementations/ConnectableObservable.swift b/RxSwift/Observables/Implementations/ConnectableObservable.swift index e02b0fcb..573d7608 100644 --- a/RxSwift/Observables/Implementations/ConnectableObservable.swift +++ b/RxSwift/Observables/Implementations/ConnectableObservable.swift @@ -27,12 +27,12 @@ public class ConnectableObservable class Connection : Disposable { - private var _lock: RecursiveLock + private var _lock: NSRecursiveLock // state private var _parent: ConnectableObservableAdapter? private var _subscription : Disposable? - init(parent: ConnectableObservableAdapter, lock: RecursiveLock, subscription: Disposable) { + init(parent: ConnectableObservableAdapter, lock: NSRecursiveLock, subscription: Disposable) { _parent = parent _subscription = subscription _lock = lock @@ -66,7 +66,7 @@ class ConnectableObservableAdapter private let _subject: S private let _source: Observable - private let _lock = RecursiveLock() + private let _lock = NSRecursiveLock() // state private var _connection: ConnectionType? diff --git a/RxSwift/Observables/Implementations/Error.swift b/RxSwift/Observables/Implementations/Error.swift index aa763838..e1322c35 100644 --- a/RxSwift/Observables/Implementations/Error.swift +++ b/RxSwift/Observables/Implementations/Error.swift @@ -9,9 +9,9 @@ import Foundation class Error : Producer { - private let _error: ErrorProtocol + private let _error: Swift.Error - init(error: ErrorProtocol) { + init(error: Swift.Error) { _error = error } diff --git a/RxSwift/Observables/Implementations/Merge.swift b/RxSwift/Observables/Implementations/Merge.swift index 617a29af..e9b86ec3 100644 --- a/RxSwift/Observables/Implementations/Merge.swift +++ b/RxSwift/Observables/Implementations/Merge.swift @@ -21,7 +21,7 @@ class MergeLimitedSinkIter: Producer { - private let _lock = RecursiveLock() + private let _lock = NSRecursiveLock() // state private var _count = 0 diff --git a/RxSwift/Observables/Implementations/RetryWhen.swift b/RxSwift/Observables/Implementations/RetryWhen.swift index 01a49c44..e5fb9f38 100644 --- a/RxSwift/Observables/Implementations/RetryWhen.swift +++ b/RxSwift/Observables/Implementations/RetryWhen.swift @@ -84,11 +84,11 @@ class RetryWhenSequenceSink - let _lock = RecursiveLock() + let _lock = NSRecursiveLock() private let _parent: Parent - private var _lastError: ErrorProtocol? + private var _lastError: Swift.Error? private let _errorSubject = PublishSubject() private let _handler: Observable private let _notifier = PublishSubject() diff --git a/RxSwift/Observables/Implementations/Sample.swift b/RxSwift/Observables/Implementations/Sample.swift index 169fa38f..4906552d 100644 --- a/RxSwift/Observables/Implementations/Sample.swift +++ b/RxSwift/Observables/Implementations/Sample.swift @@ -18,7 +18,7 @@ class SamplerSink private let _parent: Parent - let _lock = RecursiveLock() + let _lock = NSRecursiveLock() // state private var _element = nil as Element? diff --git a/RxSwift/Observables/Implementations/ShareReplay1.swift b/RxSwift/Observables/Implementations/ShareReplay1.swift index 5bb73a7c..1df1fe57 100644 --- a/RxSwift/Observables/Implementations/ShareReplay1.swift +++ b/RxSwift/Observables/Implementations/ShareReplay1.swift @@ -18,7 +18,7 @@ final class ShareReplay1 private let _source: Observable - private var _lock = RecursiveLock() + private var _lock = NSRecursiveLock() private var _connection: SingleAssignmentDisposable? private var _element: Element? diff --git a/RxSwift/Observables/Implementations/ShareReplay1WhileConnected.swift b/RxSwift/Observables/Implementations/ShareReplay1WhileConnected.swift index c47d0984..5a08396a 100644 --- a/RxSwift/Observables/Implementations/ShareReplay1WhileConnected.swift +++ b/RxSwift/Observables/Implementations/ShareReplay1WhileConnected.swift @@ -18,7 +18,7 @@ final class ShareReplay1WhileConnected private let _source: Observable - private var _lock = RecursiveLock() + private var _lock = NSRecursiveLock() private var _connection: SingleAssignmentDisposable? private var _element: Element? diff --git a/RxSwift/Observables/Implementations/SingleAsync.swift b/RxSwift/Observables/Implementations/SingleAsync.swift index 619c87be..a4c5d291 100644 --- a/RxSwift/Observables/Implementations/SingleAsync.swift +++ b/RxSwift/Observables/Implementations/SingleAsync.swift @@ -30,7 +30,7 @@ class SingleAsyncSink : S } } catch let error { - forwardOn(.error(error as ErrorProtocol)) + forwardOn(.error(error as Swift.Error)) dispose() return } diff --git a/RxSwift/Observables/Implementations/SkipUntil.swift b/RxSwift/Observables/Implementations/SkipUntil.swift index 588a52ce..ae59b7e9 100644 --- a/RxSwift/Observables/Implementations/SkipUntil.swift +++ b/RxSwift/Observables/Implementations/SkipUntil.swift @@ -17,7 +17,7 @@ class SkipUntilSinkOther - let _lock = RecursiveLock() + let _lock = NSRecursiveLock() private let _parent: Parent private var _forwardElements = false diff --git a/RxSwift/Observables/Implementations/Switch.swift b/RxSwift/Observables/Implementations/Switch.swift index ec19a7f6..5445ee38 100644 --- a/RxSwift/Observables/Implementations/Switch.swift +++ b/RxSwift/Observables/Implementations/Switch.swift @@ -18,7 +18,7 @@ class SwitchSink private let _parent: Parent - let _lock = RecursiveLock() + let _lock = NSRecursiveLock() init(parent: Parent, observer: O) { _parent = parent diff --git a/RxSwift/Observables/Implementations/TakeUntil.swift b/RxSwift/Observables/Implementations/TakeUntil.swift index 5d7cac90..d59fc8f1 100644 --- a/RxSwift/Observables/Implementations/TakeUntil.swift +++ b/RxSwift/Observables/Implementations/TakeUntil.swift @@ -17,7 +17,7 @@ class TakeUntilSinkOther private let _parent: ParentType - let _lock = RecursiveLock() + let _lock = NSRecursiveLock() // state private var _id = 0 as UInt64 diff --git a/RxSwift/Observables/Implementations/Timeout.swift b/RxSwift/Observables/Implementations/Timeout.swift index f6686563..b6f9d21c 100644 --- a/RxSwift/Observables/Implementations/Timeout.swift +++ b/RxSwift/Observables/Implementations/Timeout.swift @@ -14,7 +14,7 @@ class TimeoutSink: Sink() private var _count = 0 @@ -68,7 +68,7 @@ class WindowTimeCountSink : Sink, ZipSinkProtocol { let _arity: Int - let _lock = RecursiveLock() + let _lock = NSRecursiveLock() // state private var _isDone: [Bool] @@ -78,7 +78,7 @@ class ZipSink : Sink, ZipSinkProtocol { } } - func fail(_ error: ErrorProtocol) { + func fail(_ error: Swift.Error) { forwardOn(.error(error)) dispose() } @@ -111,14 +111,14 @@ class ZipObserver private var _parent: ZipSinkProtocol? - let _lock: RecursiveLock + let _lock: NSRecursiveLock // state private let _index: Int private let _this: Disposable private let _setNextValue: ValueSetter - init(lock: RecursiveLock, parent: ZipSinkProtocol, index: Int, setNextValue: ValueSetter, this: Disposable) { + init(lock: NSRecursiveLock, parent: ZipSinkProtocol, index: Int, setNextValue: ValueSetter, this: Disposable) { _lock = lock _parent = parent _index = index diff --git a/RxSwift/Observables/Observable+Creation.swift b/RxSwift/Observables/Observable+Creation.swift index 5b2f9385..1335e570 100644 --- a/RxSwift/Observables/Observable+Creation.swift +++ b/RxSwift/Observables/Observable+Creation.swift @@ -83,7 +83,7 @@ extension Observable { - returns: The observable sequence that terminates with specified error. */ // @warn_unused_result(message:"http://git.io/rxs.uo") - public static func error(_ error: ErrorProtocol) -> Observable { + public static func error(_ error: Swift.Error) -> Observable { return Error(error: error) } diff --git a/RxSwift/Observables/Observable+Multiple.swift b/RxSwift/Observables/Observable+Multiple.swift index 69168842..8bf90f3d 100644 --- a/RxSwift/Observables/Observable+Multiple.swift +++ b/RxSwift/Observables/Observable+Multiple.swift @@ -187,7 +187,7 @@ extension ObservableType { - returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred. */ // @warn_unused_result(message:"http://git.io/rxs.uo") - public func catchError(_ handler: (ErrorProtocol) throws -> Observable) + public func catchError(_ handler: (Swift.Error) throws -> Observable) -> Observable { return Catch(source: asObservable(), handler: handler) } diff --git a/RxSwift/Observables/Observable+Single.swift b/RxSwift/Observables/Observable+Single.swift index 4ed98d6a..faee948b 100644 --- a/RxSwift/Observables/Observable+Single.swift +++ b/RxSwift/Observables/Observable+Single.swift @@ -100,7 +100,7 @@ extension ObservableType { - returns: The source sequence with the side-effecting behavior applied. */ // @warn_unused_result(message:"http://git.io/rxs.uo") - public func doOn(onNext: ((E) throws -> Void)? = nil, onError: ((ErrorProtocol) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil) + public func doOn(onNext: ((E) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil) -> Observable { return Do(source: self.asObservable()) { e in switch e { @@ -133,7 +133,7 @@ extension ObservableType { - returns: The source sequence with the side-effecting behavior applied. */ // @warn_unused_result(message:"http://git.io/rxs.uo") - public func `do`(onError: ((ErrorProtocol) throws -> Void)) + public func `do`(onError: ((Swift.Error) throws -> Void)) -> Observable { return self.doOn(onError: onError) } @@ -214,7 +214,7 @@ extension ObservableType { - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. */ // @warn_unused_result(message:"http://git.io/rxs.uo") - public func retryWhen(_ notificationHandler: (Observable) -> TriggerObservable) + public func retryWhen(_ notificationHandler: (Observable) -> TriggerObservable) -> Observable { return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) } @@ -229,7 +229,7 @@ extension ObservableType { - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. */ // @warn_unused_result(message:"http://git.io/rxs.uo") - public func retryWhen(_ notificationHandler: (Observable) -> TriggerObservable) + public func retryWhen(_ notificationHandler: (Observable) -> TriggerObservable) -> Observable { return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) } diff --git a/RxSwift/ObserverType.swift b/RxSwift/ObserverType.swift index dc7f2d39..45a8a3ee 100644 --- a/RxSwift/ObserverType.swift +++ b/RxSwift/ObserverType.swift @@ -47,10 +47,10 @@ public extension ObserverType { } /** - Convenience method equivalent to `on(.Error(error: ErrorProtocol))` - - parameter error: ErrorProtocol to send to observer(s) + Convenience method equivalent to `on(.Error(error: Swift.Error))` + - parameter error: Swift.Error to send to observer(s) */ - final func onError(_ error: ErrorProtocol) { + final func onError(_ error: Swift.Error) { on(.error(error)) } } diff --git a/RxSwift/Platform/Platform.Darwin.swift b/RxSwift/Platform/Platform.Darwin.swift index 769cb096..9c0b3f9c 100644 --- a/RxSwift/Platform/Platform.Darwin.swift +++ b/RxSwift/Platform/Platform.Darwin.swift @@ -22,7 +22,8 @@ let AtomicDecrement = OSAtomicDecrement32 extension Thread { - static func setThreadLocalStorageValue(_ value: T?, forKey key: protocol) { + static func setThreadLocalStorageValue(_ value: T?, forKey key: AnyObject & NSCopying + ) { let currentThread = Thread.current let threadDictionary = currentThread.threadDictionary @@ -34,7 +35,7 @@ } } - static func getThreadLocalStorageValueForKey(_ key: protocol) -> T? { + static func getThreadLocalStorageValueForKey(_ key: AnyObject & NSCopying) -> T? { let currentThread = Thread.current let threadDictionary = currentThread.threadDictionary diff --git a/RxSwift/Platform/Platform.Linux.swift b/RxSwift/Platform/Platform.Linux.swift index da58b682..ff7c0434 100644 --- a/RxSwift/Platform/Platform.Linux.swift +++ b/RxSwift/Platform/Platform.Linux.swift @@ -215,7 +215,7 @@ return Expectation() } - public func waitForExpectationsWithTimeout(time: NSTimeInterval, action: ErrorProtocol? -> Void) { + public func waitForExpectationsWithTimeout(time: NSTimeInterval, action: Swift.Error? -> Void) { } } diff --git a/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift b/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift index 4c85204e..08c7bfa4 100644 --- a/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift +++ b/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift @@ -39,10 +39,11 @@ public class ConcurrentDispatchQueueScheduler: SchedulerType { */ @available(iOS 8, OSX 10.10, *) public convenience init(globalConcurrentQueueQOS: DispatchQueueSchedulerQOS, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { - let priority = globalConcurrentQueueQOS.QOSClass + let priority = globalConcurrentQueueQOS.qos self.init(queue: DispatchQueue( label: "rxswift.queue.\(globalConcurrentQueueQOS)", - attributes: [priority, DispatchQueueAttributes.concurrent], + qos: priority, + attributes: [DispatchQueue.Attributes.concurrent], target: nil), leeway: leeway ) diff --git a/RxSwift/Schedulers/DispatchQueueSchedulerQOS.swift b/RxSwift/Schedulers/DispatchQueueSchedulerQOS.swift index ca8ac94e..a8164962 100644 --- a/RxSwift/Schedulers/DispatchQueueSchedulerQOS.swift +++ b/RxSwift/Schedulers/DispatchQueueSchedulerQOS.swift @@ -42,13 +42,13 @@ public enum DispatchQueueSchedulerQOS { @available(iOS 8, OSX 10.10, *) extension DispatchQueueSchedulerQOS { - var QOSClass: DispatchQueueAttributes { + var qos: DispatchQoS { switch self { - case .userInteractive: return .qosUserInteractive - case .userInitiated: return .qosUserInitiated - case .default: return .qosDefault - case .utility: return .qosUtility - case .background: return .qosBackground + case .userInteractive: return .userInteractive + case .userInitiated: return .userInitiated + case .default: return .default + case .utility: return .utility + case .background: return .background } } } diff --git a/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift b/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift index 120a96ee..9b5c772a 100644 --- a/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift +++ b/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift @@ -41,7 +41,7 @@ extension DispatchQueueConfiguration { let compositeDisposable = CompositeDisposable() - let timer = DispatchSource.timer(queue: queue) + let timer = DispatchSource.makeTimerSource(queue: queue) timer.scheduleOneshot(deadline: deadline) // TODO: @@ -75,7 +75,7 @@ extension DispatchQueueConfiguration { var timerState = state - let timer = DispatchSource.timer(queue: queue) + let timer = DispatchSource.makeTimerSource(queue: queue) timer.scheduleRepeating(deadline: initial, interval: dispatchInterval(period), leeway: leeway) // TODO: diff --git a/RxSwift/Schedulers/RecursiveScheduler.swift b/RxSwift/Schedulers/RecursiveScheduler.swift index 473b43c1..c820b7d1 100644 --- a/RxSwift/Schedulers/RecursiveScheduler.swift +++ b/RxSwift/Schedulers/RecursiveScheduler.swift @@ -14,7 +14,7 @@ Type erased recursive scheduler. class AnyRecursiveScheduler { typealias Action = (state: State, scheduler: AnyRecursiveScheduler) -> Void - private let _lock = RecursiveLock() + private let _lock = NSRecursiveLock() // state private let _group = CompositeDisposable() diff --git a/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift b/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift index e6d69f76..09ae70a6 100644 --- a/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift +++ b/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift @@ -51,7 +51,7 @@ public class SerialDispatchQueueScheduler : SchedulerType { - parameter serialQueueConfiguration: Additional configuration of internal serial dispatch queue. */ public convenience init(internalSerialQueueName: String, serialQueueConfiguration: ((DispatchQueue) -> Void)? = nil, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { - let queue = DispatchQueue(label: internalSerialQueueName, attributes: DispatchQueueAttributes.serial) + let queue = DispatchQueue(label: internalSerialQueueName, attributes: []) serialQueueConfiguration?(queue) self.init(serialQueue: queue, leeway: leeway) } @@ -65,7 +65,7 @@ public class SerialDispatchQueueScheduler : SchedulerType { public convenience init(queue: DispatchQueue, internalSerialQueueName: String, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { // Swift 3.0 IUO let serialQueue = DispatchQueue(label: internalSerialQueueName, - attributes: DispatchQueueAttributes.serial, + attributes: [], target: queue) self.init(serialQueue: serialQueue, leeway: leeway) } @@ -78,8 +78,8 @@ public class SerialDispatchQueueScheduler : SchedulerType { */ @available(iOS 8, OSX 10.10, *) public convenience init(globalConcurrentQueueQOS: DispatchQueueSchedulerQOS, internalSerialQueueName: String = "rx.global_dispatch_queue.serial", leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { - let priority = globalConcurrentQueueQOS.QOSClass - self.init(queue: DispatchQueue.global(attributes: DispatchQueue.GlobalAttributes(rawValue: UInt64(priority.rawValue))), internalSerialQueueName: internalSerialQueueName, leeway: leeway) + let priority = globalConcurrentQueueQOS.qos + self.init(queue: DispatchQueue.global(qos: priority.qosClass), internalSerialQueueName: internalSerialQueueName, leeway: leeway) } /** diff --git a/RxSwift/Subjects/BehaviorSubject.swift b/RxSwift/Subjects/BehaviorSubject.swift index 64c0a302..b9b7e0b3 100644 --- a/RxSwift/Subjects/BehaviorSubject.swift +++ b/RxSwift/Subjects/BehaviorSubject.swift @@ -30,7 +30,7 @@ public final class BehaviorSubject return _observers.count > 0 } - let _lock = RecursiveLock() + let _lock = NSRecursiveLock() // state private var _disposed = false diff --git a/RxSwift/Subjects/PublishSubject.swift b/RxSwift/Subjects/PublishSubject.swift index f45a6984..8404c4a6 100644 --- a/RxSwift/Subjects/PublishSubject.swift +++ b/RxSwift/Subjects/PublishSubject.swift @@ -31,7 +31,7 @@ final public class PublishSubject return _observers.count > 0 } - private var _lock = RecursiveLock() + private var _lock = NSRecursiveLock() // state private var _disposed = false diff --git a/RxSwift/Subjects/ReplaySubject.swift b/RxSwift/Subjects/ReplaySubject.swift index c0082fd4..88401783 100644 --- a/RxSwift/Subjects/ReplaySubject.swift +++ b/RxSwift/Subjects/ReplaySubject.swift @@ -28,7 +28,7 @@ public class ReplaySubject return _observers.count > 0 } - private var _lock = RecursiveLock() + private var _lock = NSRecursiveLock() // state private var _disposed = false diff --git a/RxTests/XCTest+Rx.swift b/RxTests/XCTest+Rx.swift index 4588d3d9..7f4ba48c 100644 --- a/RxTests/XCTest+Rx.swift +++ b/RxTests/XCTest+Rx.swift @@ -41,7 +41,7 @@ require specifying `self.*`, they are made global. - parameter time: Recorded virtual time the `.Completed` event occurs. */ - public func error(_ time: TestTime, _ error: ErrorProtocol, _ type: T.Type = T.self) -> Recorded> { + public func error(_ time: TestTime, _ error: Swift.Error, _ type: T.Type = T.self) -> Recorded> { return Recorded(time: time, event: .error(error)) } //} diff --git a/Tests/RxCocoaTests/KVOObservableTests.swift b/Tests/RxCocoaTests/KVOObservableTests.swift index 55d5cb91..c2466cc9 100644 --- a/Tests/RxCocoaTests/KVOObservableTests.swift +++ b/Tests/RxCocoaTests/KVOObservableTests.swift @@ -991,7 +991,7 @@ extension KVOObservableTests { func testObserveWeak_PropertyDoesntExist() { var root: HasStrongProperty! = HasStrongProperty() - var lastError: ErrorProtocol? = nil + var lastError: Swift.Error? = nil _ = root.rx_observeWeakly(NSNumber.self, "notExist") .subscribeError { error in @@ -1017,7 +1017,7 @@ extension KVOObservableTests { func testObserveWeak_HierarchyPropertyDoesntExist() { var root: HasStrongProperty! = HasStrongProperty() - var lastError: ErrorProtocol? = nil + var lastError: Swift.Error? = nil _ = root.rx_observeWeakly(NSNumber.self, "property.notExist") .subscribeError { error in diff --git a/Tests/RxSwiftTests/TestImplementations/Mocks/PrimitiveHotObservable.swift b/Tests/RxSwiftTests/TestImplementations/Mocks/PrimitiveHotObservable.swift index ef9229cb..af5f47db 100644 --- a/Tests/RxSwiftTests/TestImplementations/Mocks/PrimitiveHotObservable.swift +++ b/Tests/RxSwiftTests/TestImplementations/Mocks/PrimitiveHotObservable.swift @@ -22,7 +22,7 @@ class PrimitiveHotObservable : ObservableType { var subscriptions: [Subscription] var observers: Bag> - let lock = RecursiveLock() + let lock = NSRecursiveLock() init() { self.subscriptions = [] diff --git a/Tests/RxSwiftTests/Tests/Observable+SingleTest.swift b/Tests/RxSwiftTests/Tests/Observable+SingleTest.swift index a682e3c5..a4f7d9bd 100644 --- a/Tests/RxSwiftTests/Tests/Observable+SingleTest.swift +++ b/Tests/RxSwiftTests/Tests/Observable+SingleTest.swift @@ -644,7 +644,7 @@ extension ObservableSingleTest { error(250, testError) ]) - var recordedError: ErrorProtocol! + var recordedError: Swift.Error! var numberOfTimesInvoked = 0 let res = scheduler.start { xs.do(onError: { error in @@ -995,7 +995,7 @@ extension ObservableSingleTest { } } -struct CustomErrorType : ErrorProtocol { +struct CustomErrorType : Swift.Error { } @@ -1305,7 +1305,7 @@ extension ObservableSingleTest { let maxAttempts = 4 let res = scheduler.start(800) { - xs.retryWhen { (errors: Observable) in + xs.retryWhen { (errors: Observable) in return errors.flatMapWithIndex { (e, a) -> Observable in if a >= maxAttempts - 1 { return Observable.error(e) diff --git a/Tests/RxSwiftTests/Tests/Observable+SubscriptionTest.swift b/Tests/RxSwiftTests/Tests/Observable+SubscriptionTest.swift index 9b842bc4..51794ade 100644 --- a/Tests/RxSwiftTests/Tests/Observable+SubscriptionTest.swift +++ b/Tests/RxSwiftTests/Tests/Observable+SubscriptionTest.swift @@ -20,7 +20,7 @@ class ObservableSubscriptionTests : RxTest { var onDisposedCalled = 0 var lastElement: Int? = nil - var lastError: ErrorProtocol? = nil + var lastError: Swift.Error? = nil let subscription = publishSubject.subscribe(onNext: { n in lastElement = n @@ -70,7 +70,7 @@ class ObservableSubscriptionTests : RxTest { var onDisposedCalled = 0 var lastElement: Int? = nil - var lastError: ErrorProtocol? = nil + var lastError: Swift.Error? = nil let subscription = publishSubject.subscribe(onNext: { n in lastElement = n @@ -121,7 +121,7 @@ class ObservableSubscriptionTests : RxTest { var onDisposedCalled = 0 var lastElement: Int? = nil - var lastError: ErrorProtocol? = nil + var lastError: Swift.Error? = nil let subscription = publishSubject.subscribe(onNext: { n in lastElement = n @@ -172,7 +172,7 @@ class ObservableSubscriptionTests : RxTest { var onDisposedCalled = 0 var lastElement: Int? = nil - var lastError: ErrorProtocol? = nil + var lastError: Swift.Error? = nil let subscription = publishSubject.subscribe(onNext: { n in lastElement = n diff --git a/Tests/RxSwiftTests/Tests/ObserverTests.swift b/Tests/RxSwiftTests/Tests/ObserverTests.swift index a7d32cde..57214ea5 100644 --- a/Tests/RxSwiftTests/Tests/ObserverTests.swift +++ b/Tests/RxSwiftTests/Tests/ObserverTests.swift @@ -42,7 +42,7 @@ extension ObserverTests { } var elements = [Int]() - var errorNotification: ErrorProtocol! + var errorNotification: Swift.Error! _ = a.subscribe( onNext: { n in elements.append(n) }, diff --git a/Tests/Tests/Recorded+Timeless.swift b/Tests/Tests/Recorded+Timeless.swift index 04983d82..6f2b3773 100644 --- a/Tests/Tests/Recorded+Timeless.swift +++ b/Tests/Tests/Recorded+Timeless.swift @@ -18,6 +18,6 @@ func completed() -> Recorded> { return Recorded(time: 0, event: .completed) } -func error(_ error: ErrorProtocol) -> Recorded> { +func error(_ error: Swift.Error) -> Recorded> { return Recorded(time: 0, event: .error(error)) } diff --git a/Tests/Tests/XCTest+AllTests.swift b/Tests/Tests/XCTest+AllTests.swift index 1495e7ae..15c8f5d2 100644 --- a/Tests/Tests/XCTest+AllTests.swift +++ b/Tests/Tests/XCTest+AllTests.swift @@ -11,7 +11,7 @@ import RxSwift import RxTests import XCTest -func XCTAssertErrorEqual(_ lhs: ErrorProtocol, _ rhs: ErrorProtocol) { +func XCTAssertErrorEqual(_ lhs: Swift.Error, _ rhs: Swift.Error) { let event1: Event = .error(lhs) let event2: Event = .error(rhs) From a9d0cfeb5bc4f16f7b955bc714decf43524faae6 Mon Sep 17 00:00:00 2001 From: Yuki Nagai Date: Tue, 2 Aug 2016 21:48:01 +0900 Subject: [PATCH 08/52] Add Error extension instead of NSError for Workaround; NSError extension returns a type which conforms to Error protocol --- RxCocoa/Common/Observables/NSObject+Rx.swift | 12 ++---------- RxCocoa/Common/RxCocoa.swift | 14 ++++++++------ 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/RxCocoa/Common/Observables/NSObject+Rx.swift b/RxCocoa/Common/Observables/NSObject+Rx.swift index fcaff000..3539aa3b 100644 --- a/RxCocoa/Common/Observables/NSObject+Rx.swift +++ b/RxCocoa/Common/Observables/NSObject+Rx.swift @@ -126,10 +126,6 @@ extension NSObject { - returns: Observable sequence of object deallocating events. */ public func rx_sentMessage(_ selector: Selector) -> Observable<[AnyObject]> { - return Observable.create { _ in - return AnonymousDisposable {} - } - /* return rx_synchronized { // in case of dealloc selector replay subject behavior needs to be used if selector == deallocSelector { @@ -164,7 +160,7 @@ extension NSObject { subject.targetImplementation = targetImplementation return subject.asObservable() - }*/ + } } /** @@ -178,10 +174,6 @@ extension NSObject { - returns: Observable sequence of object deallocating events. */ public var rx_deallocating: Observable<()> { - return Observable.create { _ in - return AnonymousDisposable {} - } - /* return rx_synchronized { let subject: DeallocatingObservable @@ -210,7 +202,7 @@ extension NSObject { subject.targetImplementation = targetImplementation! return subject.asObservable() - }*/ + } } #endif } diff --git a/RxCocoa/Common/RxCocoa.swift b/RxCocoa/Common/RxCocoa.swift index 5aba2e45..28ba7add 100644 --- a/RxCocoa/Common/RxCocoa.swift +++ b/RxCocoa/Common/RxCocoa.swift @@ -296,16 +296,18 @@ let delegateNotSet = "Delegate not set" // MARK: Conversions `NSError` > `RxCocoaObjCRuntimeError` -extension NSError { +extension Error { func rxCocoaErrorForTarget(_ target: AnyObject) -> RxCocoaObjCRuntimeError { - if domain == RXObjCRuntimeErrorDomain { - let errorCode = RXObjCRuntimeError(rawValue: self.code) ?? .unknown - + let error = self as NSError + + if error.domain == RXObjCRuntimeErrorDomain { + let errorCode = RXObjCRuntimeError(rawValue: error.code) ?? .unknown + switch errorCode { case .unknown: return .unknown(target: target) case .objectMessagesAlreadyBeingIntercepted: - let isKVO = (self.userInfo[RXObjCRuntimeErrorIsKVOKey] as? NSNumber)?.boolValue ?? false + let isKVO = (error.userInfo[RXObjCRuntimeErrorIsKVOKey] as? NSNumber)?.boolValue ?? false return .objectMessagesAlreadyBeingIntercepted(target: target, interceptionMechanism: isKVO ? .kvo : .unknown) case .selectorNotImplemented: return .selectorNotImplemented(target: target) @@ -323,7 +325,7 @@ extension NSError { return .observingMessagesWithUnsupportedReturnType(target: target) } } - + return RxCocoaObjCRuntimeError.unknown(target: target) } } From 21a56a8ebde4096487f0faafdba6ea011c6c784e Mon Sep 17 00:00:00 2001 From: Krunoslav Zaher Date: Tue, 2 Aug 2016 14:51:04 +0200 Subject: [PATCH 09/52] Fixes all tests. --- scripts/validate-headers.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/validate-headers.swift b/scripts/validate-headers.swift index 67aab7c0..51ba5f24 100755 --- a/scripts/validate-headers.swift +++ b/scripts/validate-headers.swift @@ -23,7 +23,7 @@ Validates that all headers are in this standard form Only Project is not checked yet, but it will be soon. */ -let fileManager = FileManager.default() +let fileManager = FileManager.default let allowedExtensions = [ ".swift", From 72e5488631579c3ae0401e160cac84659f9fc6ed Mon Sep 17 00:00:00 2001 From: LZL Date: Wed, 3 Aug 2016 17:27:15 +0800 Subject: [PATCH 10/52] Typo --- Documentation/GettingStarted.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/GettingStarted.md b/Documentation/GettingStarted.md index 79f8a040..fad28786 100644 --- a/Documentation/GettingStarted.md +++ b/Documentation/GettingStarted.md @@ -133,7 +133,7 @@ This will print: 5 ``` -Note the you usually do not want to manually call `dispose`; this is only educational example. Calling dispose manually is usually a bad code smell. There are better ways to dispose subscriptions. We can use `DisposeBag`, the `takeUntil` operator, or some other mechanism. +Note that you usually do not want to manually call `dispose`; this is only educational example. Calling dispose manually is usually a bad code smell. There are better ways to dispose subscriptions. We can use `DisposeBag`, the `takeUntil` operator, or some other mechanism. So can this code print something after the `dispose` call executed? The answer is: it depends. From 2ead37809efdc3794684305a6e3b0be889c497d1 Mon Sep 17 00:00:00 2001 From: Krunoslav Zaher Date: Thu, 4 Aug 2016 10:44:46 +0200 Subject: [PATCH 11/52] Fixes example app compiling. --- .../UISectionedViewType+RxAnimatedDataSource.swift | 4 ++-- .../RxDataSources/DataSources/AnimatableSectionModel.swift | 2 +- RxExample/RxDataSources/DataSources/Differentiator.swift | 2 +- .../GeolocationExample/GeolocationViewController.swift | 2 +- .../GitHubSearchRepositoriesAPI.swift | 6 +++--- .../GitHubSearchRepositoriesViewController.swift | 4 ++-- .../RxExample/Examples/GitHubSignup/BindingExtensions.swift | 6 +++--- .../ImagePicker/UIImagePickerController+RxCreate.swift | 2 +- .../TableViewWithEditingCommandsViewController.swift | 6 +++--- .../UIImageView+Extensions.swift | 2 +- .../Views/WikipediaSearchViewController.swift | 6 +++--- RxExample/RxExample/Services/HtmlParsing.swift | 6 +++--- RxExample/RxExample/Services/ImageService.swift | 4 ++-- RxExample/RxExample/Services/Reachability.swift | 2 +- RxExample/RxExample/Services/ReachabilityService.swift | 2 +- RxExample/RxExample/Services/Wireframe.swift | 4 ++-- 16 files changed, 30 insertions(+), 30 deletions(-) diff --git a/RxExample/RxDataSources/DataSources+Rx/UISectionedViewType+RxAnimatedDataSource.swift b/RxExample/RxDataSources/DataSources+Rx/UISectionedViewType+RxAnimatedDataSource.swift index 171b2504..08689914 100644 --- a/RxExample/RxDataSources/DataSources+Rx/UISectionedViewType+RxAnimatedDataSource.swift +++ b/RxExample/RxDataSources/DataSources+Rx/UISectionedViewType+RxAnimatedDataSource.swift @@ -16,7 +16,7 @@ import RxCocoa extension UITableView { @available(*, deprecated:0.7, renamed:"rx_itemsWithDataSource", message:"You can just use normal `rx_itemsWithDataSource` extension.") public func rx_itemsAnimatedWithDataSource< - DataSource: protocol, + DataSource: RxTableViewDataSourceType & UITableViewDataSource, S: Sequence, O: ObservableType where @@ -36,7 +36,7 @@ extension UITableView { extension UICollectionView { @available(*, deprecated:0.7, renamed:"rx_itemsWithDataSource", message:"You can just use normal `rx_itemsWithDataSource` extension.") public func rx_itemsAnimatedWithDataSource< - DataSource: protocol, + DataSource: RxCollectionViewDataSourceType & UICollectionViewDataSource, S: Sequence, O: ObservableType where diff --git a/RxExample/RxDataSources/DataSources/AnimatableSectionModel.swift b/RxExample/RxDataSources/DataSources/AnimatableSectionModel.swift index c5a50bca..b2466798 100644 --- a/RxExample/RxDataSources/DataSources/AnimatableSectionModel.swift +++ b/RxExample/RxDataSources/DataSources/AnimatableSectionModel.swift @@ -8,7 +8,7 @@ import Foundation -public struct AnimatableSectionModel> +public struct AnimatableSectionModel : AnimatableSectionModelType , CustomStringConvertible { public typealias Item = ItemType diff --git a/RxExample/RxDataSources/DataSources/Differentiator.swift b/RxExample/RxDataSources/DataSources/Differentiator.swift index e3077b8a..79e33bb5 100644 --- a/RxExample/RxDataSources/DataSources/Differentiator.swift +++ b/RxExample/RxDataSources/DataSources/Differentiator.swift @@ -23,7 +23,7 @@ extension DifferentiatorError { return "Duplicate item \(item)" case let .duplicateSection(section): return "Duplicate section \(section)" - case let invalidInitializerImplementation(section, expectedItems, expectedIdentifier): + case let .invalidInitializerImplementation(section, expectedItems, expectedIdentifier): return "Wrong initializer implementation for: \(section)\n" + "Expected it should return items: \(expectedItems)\n" + "Expected it should have id: \(expectedIdentifier)" diff --git a/RxExample/RxExample/Examples/GeolocationExample/GeolocationViewController.swift b/RxExample/RxExample/Examples/GeolocationExample/GeolocationViewController.swift index 246b161e..629cc893 100644 --- a/RxExample/RxExample/Examples/GeolocationExample/GeolocationViewController.swift +++ b/RxExample/RxExample/Examples/GeolocationExample/GeolocationViewController.swift @@ -70,7 +70,7 @@ class GeolocationViewController: ViewController { } private func openAppPreferences() { - UIApplication.shared().openURL(URL(string: UIApplicationOpenSettingsURLString)!) + UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!) } } diff --git a/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesAPI.swift b/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesAPI.swift index 031ff8e2..c3a380fc 100644 --- a/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesAPI.swift +++ b/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesAPI.swift @@ -195,18 +195,18 @@ extension GitHubSearchRepositoriesAPI { extension GitHubSearchRepositoriesAPI { private static let parseLinksPattern = "\\s*,?\\s*<([^\\>]*)>\\s*;\\s*rel=\"([^\"]*)\"" - private static let linksRegex = try! RegularExpression(pattern: parseLinksPattern, options: [.allowCommentsAndWhitespace]) + private static let linksRegex = try! NSRegularExpression(pattern: parseLinksPattern, options: [.allowCommentsAndWhitespace]) private static func parseLinks(_ links: String) throws -> [String: String] { let length = (links as NSString).length - let matches = GitHubSearchRepositoriesAPI.linksRegex.matches(in: links, options: RegularExpression.MatchingOptions(), range: NSRange(location: 0, length: length)) + let matches = GitHubSearchRepositoriesAPI.linksRegex.matches(in: links, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: length)) var result: [String: String] = [:] for m in matches { let matches = (1 ..< m.numberOfRanges).map { rangeIndex -> String in - let range = m.range(at: rangeIndex) + let range = m.rangeAt(rangeIndex) let startIndex = links.characters.index(links.startIndex, offsetBy: range.location) let endIndex = links.characters.index(links.startIndex, offsetBy: range.location + range.length) let stringRange = startIndex ..< endIndex diff --git a/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesViewController.swift b/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesViewController.swift index 75ba6247..23d1e444 100644 --- a/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesViewController.swift +++ b/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesViewController.swift @@ -87,7 +87,7 @@ class GitHubSearchRepositoriesViewController: ViewController, UITableViewDelegat // dismiss keyboard on scroll tableView.rx_contentOffset .subscribe { _ in - if self.searchBar.isFirstResponder() { + if self.searchBar.isFirstResponder { _ = self.searchBar.resignFirstResponder() } } @@ -100,7 +100,7 @@ class GitHubSearchRepositoriesViewController: ViewController, UITableViewDelegat // activity indicator in status bar // { GitHubSearchRepositoriesAPI.sharedAPI.activityIndicator - .drive(UIApplication.shared().rx_networkActivityIndicatorVisible) + .drive(UIApplication.shared.rx_networkActivityIndicatorVisible) .addDisposableTo(disposeBag) // } } diff --git a/RxExample/RxExample/Examples/GitHubSignup/BindingExtensions.swift b/RxExample/RxExample/Examples/GitHubSignup/BindingExtensions.swift index 804146d6..9c87522d 100644 --- a/RxExample/RxExample/Examples/GitHubSignup/BindingExtensions.swift +++ b/RxExample/RxExample/Examples/GitHubSignup/BindingExtensions.swift @@ -30,7 +30,7 @@ extension ValidationResult: CustomStringConvertible { struct ValidationColors { static let okColor = UIColor(red: 138.0 / 255.0, green: 221.0 / 255.0, blue: 109.0 / 255.0, alpha: 1.0) - static let errorColor = UIColor.red() + static let errorColor = UIColor.red } extension ValidationResult { @@ -39,9 +39,9 @@ extension ValidationResult { case .ok: return ValidationColors.okColor case .empty: - return UIColor.black() + return UIColor.black case .validating: - return UIColor.black() + return UIColor.black case .failed: return ValidationColors.errorColor } diff --git a/RxExample/RxExample/Examples/ImagePicker/UIImagePickerController+RxCreate.swift b/RxExample/RxExample/Examples/ImagePicker/UIImagePickerController+RxCreate.swift index 3b031788..03998b27 100644 --- a/RxExample/RxExample/Examples/ImagePicker/UIImagePickerController+RxCreate.swift +++ b/RxExample/RxExample/Examples/ImagePicker/UIImagePickerController+RxCreate.swift @@ -14,7 +14,7 @@ import UIKit #endif func dismissViewController(_ viewController: UIViewController, animated: Bool) { - if viewController.isBeingDismissed() || viewController.isBeingPresented() { + if viewController.isBeingDismissed || viewController.isBeingPresented { DispatchQueue.main.async { dismissViewController(viewController, animated: animated) } diff --git a/RxExample/RxExample/Examples/TableViewWithEditingCommands/TableViewWithEditingCommandsViewController.swift b/RxExample/RxExample/Examples/TableViewWithEditingCommands/TableViewWithEditingCommandsViewController.swift index 3aa03b6a..02dce321 100644 --- a/RxExample/RxExample/Examples/TableViewWithEditingCommands/TableViewWithEditingCommandsViewController.swift +++ b/RxExample/RxExample/Examples/TableViewWithEditingCommands/TableViewWithEditingCommandsViewController.swift @@ -62,7 +62,7 @@ class TableViewWithEditingCommandsViewController: ViewController, UITableViewDel override func viewDidLoad() { super.viewDidLoad() - self.navigationItem.rightBarButtonItem = self.editButtonItem() + self.navigationItem.rightBarButtonItem = self.editButtonItem let superMan = User( firstName: "Super", @@ -139,8 +139,8 @@ class TableViewWithEditingCommandsViewController: ViewController, UITableViewDel let label = UILabel(frame: CGRect.zero) // hacky I know :) label.text = " \(title)" - label.textColor = UIColor.white() - label.backgroundColor = UIColor.darkGray() + label.textColor = UIColor.white + label.backgroundColor = UIColor.darkGray label.alpha = 0.9 return label diff --git a/RxExample/RxExample/Examples/TableViewWithEditingCommands/UIImageView+Extensions.swift b/RxExample/RxExample/Examples/TableViewWithEditingCommands/UIImageView+Extensions.swift index 79f17aea..553337e8 100644 --- a/RxExample/RxExample/Examples/TableViewWithEditingCommands/UIImageView+Extensions.swift +++ b/RxExample/RxExample/Examples/TableViewWithEditingCommands/UIImageView+Extensions.swift @@ -12,7 +12,7 @@ extension UIImageView { func makeRoundedCorners(_ radius: CGFloat) { self.layer.cornerRadius = self.frame.size.width / 2 - self.layer.borderColor = UIColor.darkGray().cgColor + self.layer.borderColor = UIColor.darkGray.cgColor self.layer.borderWidth = radius self.layer.masksToBounds = true } diff --git a/RxExample/RxExample/Examples/WikipediaImageSearch/Views/WikipediaSearchViewController.swift b/RxExample/RxExample/Examples/WikipediaImageSearch/Views/WikipediaSearchViewController.swift index dcface30..2f0a872b 100644 --- a/RxExample/RxExample/Examples/WikipediaImageSearch/Views/WikipediaSearchViewController.swift +++ b/RxExample/RxExample/Examples/WikipediaImageSearch/Views/WikipediaSearchViewController.swift @@ -91,10 +91,10 @@ class WikipediaSearchViewController: ViewController { resultsTableView.rx_contentOffset .asDriver() .filter { _ -> Bool in - return !searchController.isBeingPresented() + return !searchController.isBeingPresented } .driveNext { _ in - if searchBar.isFirstResponder() { + if searchBar.isFirstResponder { _ = searchBar.resignFirstResponder() } } @@ -118,7 +118,7 @@ class WikipediaSearchViewController: ViewController { DefaultImageService.sharedImageService.loadingImage ) { $0 || $1 } .distinctUntilChanged() - .drive(UIApplication.shared().rx_networkActivityIndicatorVisible) + .drive(UIApplication.shared.rx_networkActivityIndicatorVisible) .addDisposableTo(disposeBag) } } diff --git a/RxExample/RxExample/Services/HtmlParsing.swift b/RxExample/RxExample/Services/HtmlParsing.swift index c75ccb59..1747b005 100644 --- a/RxExample/RxExample/Services/HtmlParsing.swift +++ b/RxExample/RxExample/Services/HtmlParsing.swift @@ -9,7 +9,7 @@ import Foundation func parseImageURLsfromHTML(_ html: NSString) throws -> [URL] { - let regularExpression = try RegularExpression(pattern: "]*src=\"([^\"]+)\"[^>]*>", options: []) + let regularExpression = try NSRegularExpression(pattern: "]*src=\"([^\"]+)\"[^>]*>", options: []) let matches = regularExpression.matches(in: html as String, options: [], range: NSMakeRange(0, html.length)) @@ -18,7 +18,7 @@ func parseImageURLsfromHTML(_ html: NSString) throws -> [URL] { return nil } - let url = html.substring(with: match.range(at: 1)) + let url = html.substring(with: match.rangeAt(1)) var absoluteURLString = url if url.hasPrefix("//") { @@ -31,6 +31,6 @@ func parseImageURLsfromHTML(_ html: NSString) throws -> [URL] { func parseImageURLsfromHTMLSuitableForDisplay(_ html: NSString) throws -> [URL] { return try parseImageURLsfromHTML(html).filter { - return $0.absoluteString?.range(of: ".svg.") == nil + return $0.absoluteString.range(of: ".svg.") == nil } } diff --git a/RxExample/RxExample/Services/ImageService.swift b/RxExample/RxExample/Services/ImageService.swift index 82ca0057..3d99c636 100644 --- a/RxExample/RxExample/Services/ImageService.swift +++ b/RxExample/RxExample/Services/ImageService.swift @@ -29,10 +29,10 @@ class DefaultImageService: ImageService { let $: Dependencies = Dependencies.sharedDependencies // 1st level cache - private let _imageCache = Cache() + private let _imageCache = NSCache() // 2nd level cache - private let _imageDataCache = Cache() + private let _imageDataCache = NSCache() let loadingImage = ActivityIndicator() diff --git a/RxExample/RxExample/Services/Reachability.swift b/RxExample/RxExample/Services/Reachability.swift index ea000464..464e38b8 100644 --- a/RxExample/RxExample/Services/Reachability.swift +++ b/RxExample/RxExample/Services/Reachability.swift @@ -224,7 +224,7 @@ public class Reachability: NSObject { private var notifierRunning = false private var reachabilityRef: SCNetworkReachability? - private let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability", attributes: DispatchQueueAttributes.serial) + private let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability") private func reachabilityChanged(_ flags: SCNetworkReachabilityFlags) { if isReachableWithFlags(flags) { diff --git a/RxExample/RxExample/Services/ReachabilityService.swift b/RxExample/RxExample/Services/ReachabilityService.swift index e6387208..f851f12b 100644 --- a/RxExample/RxExample/Services/ReachabilityService.swift +++ b/RxExample/RxExample/Services/ReachabilityService.swift @@ -47,7 +47,7 @@ class DefaultReachabilityService let reachabilitySubject = BehaviorSubject(value: .unreachable) // so main thread isn't blocked when reachability via WiFi is checked - let backgroundQueue = DispatchQueue(label: "reachability.wificheck", attributes: DispatchQueueAttributes.serial) + let backgroundQueue = DispatchQueue(label: "reachability.wificheck") reachabilityRef.whenReachable = { reachability in backgroundQueue.async { diff --git a/RxExample/RxExample/Services/Wireframe.swift b/RxExample/RxExample/Services/Wireframe.swift index 61dbddea..bb36e5fe 100644 --- a/RxExample/RxExample/Services/Wireframe.swift +++ b/RxExample/RxExample/Services/Wireframe.swift @@ -33,7 +33,7 @@ class DefaultWireframe: Wireframe { func open(url: URL) { #if os(iOS) - UIApplication.shared().openURL(url) + UIApplication.shared.openURL(url) #elseif os(OSX) NSWorkspace.shared().open(url) #endif @@ -42,7 +42,7 @@ class DefaultWireframe: Wireframe { #if os(iOS) private static func rootViewController() -> UIViewController { // cheating, I know - return UIApplication.shared().keyWindow!.rootViewController! + return UIApplication.shared.keyWindow!.rootViewController! } #endif From 01d86ff684b060b984b7b8c12305efd677fa728b Mon Sep 17 00:00:00 2001 From: Krunoslav Zaher Date: Thu, 4 Aug 2016 10:48:36 +0200 Subject: [PATCH 12/52] Fixes OSX compilation issues. --- RxExample/RxExample/ViewController.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/RxExample/RxExample/ViewController.swift b/RxExample/RxExample/ViewController.swift index 76b8debe..1b6d6fb2 100644 --- a/RxExample/RxExample/ViewController.swift +++ b/RxExample/RxExample/ViewController.swift @@ -37,7 +37,7 @@ class ViewController: OSViewController { } deinit { -#if TRACE_RESOURCES +#if TRACE_RESOURCES && os(iOS) print("View controller disposed with \(resourceCount) resources") /* @@ -79,8 +79,8 @@ class ViewController: OSViewController { If somebody knows more about why this delay happens, you can make a PR with explanation here. */ - let when = DispatchTime.now() + DispatchTimeInterval.milliseconds(2) - mainQueue.after(when: when) { + let when = DispatchTime.now() + DispatchTimeInterval.milliseconds(20) + mainQueue.after (when: when) { /* Some small additional period to clean things up. In case there were async operations fired, From 38c45c066d101a8be750a3fdb5c706448abeab06 Mon Sep 17 00:00:00 2001 From: Krunoslav Zaher Date: Thu, 4 Aug 2016 10:56:09 +0200 Subject: [PATCH 13/52] Example compilation fixes. --- RxExample/RxExample/ViewController.swift | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/RxExample/RxExample/ViewController.swift b/RxExample/RxExample/ViewController.swift index 1b6d6fb2..3bfce507 100644 --- a/RxExample/RxExample/ViewController.swift +++ b/RxExample/RxExample/ViewController.swift @@ -37,7 +37,7 @@ class ViewController: OSViewController { } deinit { -#if TRACE_RESOURCES && os(iOS) +#if TRACE_RESOURCES print("View controller disposed with \(resourceCount) resources") /* @@ -80,7 +80,8 @@ class ViewController: OSViewController { If somebody knows more about why this delay happens, you can make a PR with explanation here. */ let when = DispatchTime.now() + DispatchTimeInterval.milliseconds(20) - mainQueue.after (when: when) { + + mainQueue.asyncAfter (deadline: when) { /* Some small additional period to clean things up. In case there were async operations fired, From a2ee04e721f0fab03ebf44a1543f1ff737db635b Mon Sep 17 00:00:00 2001 From: Krunoslav Zaher Date: Thu, 4 Aug 2016 11:12:53 +0200 Subject: [PATCH 14/52] Fixes unit tests. --- Rx.xcodeproj/project.pbxproj | 8 ++++- .../RxCocoaTests/Control+RxTests+UIKit.swift | 12 +++---- Tests/RxCocoaTests/Driver+Test.swift | 4 +-- Tests/RxCocoaTests/SentMessageTest.swift | 12 +++---- Tests/RxSwiftTests/Tests/BagTest.swift | 8 ++--- Tests/RxSwiftTests/Tests/DisposableTest.swift | 2 +- .../Tests/Observable+ConcurrencyTest.swift | 4 +-- .../Tests/Observable+MultipleTest.swift | 32 +++++++++---------- .../Tests/Observable+SingleTest.swift | 2 +- Tests/RxSwiftTests/Tests/SchedulerTests.swift | 4 +-- .../Tests/SubjectConcurrencyTest.swift | 2 +- Tests/RxTest.swift | 2 +- Tests/Tests/XCTest+AllTests.swift | 2 +- 13 files changed, 50 insertions(+), 44 deletions(-) diff --git a/Rx.xcodeproj/project.pbxproj b/Rx.xcodeproj/project.pbxproj index 9ae9ce93..0b6a3737 100644 --- a/Rx.xcodeproj/project.pbxproj +++ b/Rx.xcodeproj/project.pbxproj @@ -3141,7 +3141,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0720; - LastUpgradeCheck = 0720; + LastUpgradeCheck = 0800; ORGANIZATIONNAME = "Krunoslav Zaher"; TargetAttributes = { C80938F51B8A71760088E94D = { @@ -5245,8 +5245,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -5640,8 +5642,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -5697,8 +5701,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; diff --git a/Tests/RxCocoaTests/Control+RxTests+UIKit.swift b/Tests/RxCocoaTests/Control+RxTests+UIKit.swift index e4bf2757..adec6a83 100644 --- a/Tests/RxCocoaTests/Control+RxTests+UIKit.swift +++ b/Tests/RxCocoaTests/Control+RxTests+UIKit.swift @@ -59,17 +59,17 @@ extension ControlTests { // UILabel extension ControlTests { func testLabel_HasWeakReference() { - let variable = Variable(nil) - ensureControlObserverHasWeakReference(UILabel(), { (label: UILabel) -> AnyObserver in label.rx_attributedText }, { variable.asObservable() }) + let variable = Variable(nil) + ensureControlObserverHasWeakReference(UILabel(), { (label: UILabel) -> AnyObserver in label.rx_attributedText }, { variable.asObservable() }) } func testLabel_NextElementsSetsValue() { let subject = UILabel() - let attributedTextSequence = Variable(nil) + let attributedTextSequence = Variable(nil) let disposable = attributedTextSequence.asObservable().bindTo(subject.rx_attributedText) defer { disposable.dispose() } - attributedTextSequence.value = AttributedString(string: "Hello!") + attributedTextSequence.value = NSAttributedString(string: "Hello!") XCTAssert(subject.attributedText == attributedTextSequence.value, "Expected attributedText to have been set") } } @@ -137,10 +137,10 @@ extension ControlTests { defer { disposable.dispose() } boolSequence.value = true - XCTAssertTrue(subject.isAnimating(), "Expected animation to be started") + XCTAssertTrue(subject.isAnimating, "Expected animation to be started") boolSequence.value = false - XCTAssertFalse(subject.isAnimating(), "Expected animation to be stopped") + XCTAssertFalse(subject.isAnimating, "Expected animation to be stopped") } } diff --git a/Tests/RxCocoaTests/Driver+Test.swift b/Tests/RxCocoaTests/Driver+Test.swift index efa89e3c..59dfd0f2 100644 --- a/Tests/RxCocoaTests/Driver+Test.swift +++ b/Tests/RxCocoaTests/Driver+Test.swift @@ -861,7 +861,7 @@ extension DriverTest { let hotObservable1 = BackgroundThreadPrimitiveHotObservable() let hotObservable2 = BackgroundThreadPrimitiveHotObservable() - let driver = [hotObservable1.asDriver(onErrorJustReturn: -1), hotObservable2.asDriver(onErrorJustReturn: -2)].combineLatest { a in a.reduce(0, combine: +) } + let driver = [hotObservable1.asDriver(onErrorJustReturn: -1), hotObservable2.asDriver(onErrorJustReturn: -2)].combineLatest { a in a.reduce(0, +) } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable]) @@ -916,7 +916,7 @@ extension DriverTest { let hotObservable1 = BackgroundThreadPrimitiveHotObservable() let hotObservable2 = BackgroundThreadPrimitiveHotObservable() - let driver = [hotObservable1.asDriver(onErrorJustReturn: -1), hotObservable2.asDriver(onErrorJustReturn: -2)].zip { a in a.reduce(0, combine: +) } + let driver = [hotObservable1.asDriver(onErrorJustReturn: -1), hotObservable2.asDriver(onErrorJustReturn: -2)].zip { a in a.reduce(0, +) } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(driver) { XCTAssertTrue(hotObservable1.subscriptions == [SubscribedToHotObservable]) diff --git a/Tests/RxCocoaTests/SentMessageTest.swift b/Tests/RxCocoaTests/SentMessageTest.swift index 8a695db9..f99f5156 100644 --- a/Tests/RxCocoaTests/SentMessageTest.swift +++ b/Tests/RxCocoaTests/SentMessageTest.swift @@ -361,8 +361,8 @@ extension SentMessageTest { func _baseClass_subClass_dont_interact_for_optimized_version < - BaseClass: protocol, - TargetClass: protocol + BaseClass: SentMessageTestClassCreationProtocol & NSObjectProtocol, + TargetClass: SentMessageTestClassCreationProtocol & NSObjectProtocol >(_ baseClass: BaseClass.Type, _ targetClass: TargetClass.Type, _ method: Selector, _ invoke: (BaseClass) -> [[MethodParameters]]) { // now force forwarding mechanism for normal class ensureGlobalRuntimeChangesAreCached( @@ -928,7 +928,7 @@ extension SentMessageTest { Repeats action twice and makes sure there is no global leaks. Observing mechanism is lazy loaded so not caching results properly can cause serious memory leaks. */ - func ensureGlobalRuntimeChangesAreCached>( + func ensureGlobalRuntimeChangesAreCached( _ createIt: () -> T, observeIt: (T) -> [Observable], objectActingClassChange: [ObjectRuntimeChange], @@ -960,7 +960,7 @@ extension SentMessageTest { } - func _ensureGlobalRuntimeChangesAreCached>( + func _ensureGlobalRuntimeChangesAreCached ( _ createIt: () -> T, observeIt: (T) -> [Observable], expectedActingClassChanges: [ObjectRuntimeChange], @@ -1058,7 +1058,7 @@ extension SentMessageTest { } - func createKVODynamicSubclassed>(_ type: T.Type = T.self) -> () -> (T, [Disposable]) { + func createKVODynamicSubclassed(_ type: T.Type = T.self) -> () -> (T, [Disposable]) { return { let t = T.createInstance() //let disposable = (t as! NSObject).rx_observe(NSArray.self, "messages").publish().connect() @@ -1067,7 +1067,7 @@ extension SentMessageTest { } } - func createNormalInstance>(_ type: T.Type = T.self) -> () -> T { + func createNormalInstance(_ type: T.Type = T.self) -> () -> T { return { return T.createInstance() } diff --git a/Tests/RxSwiftTests/Tests/BagTest.swift b/Tests/RxSwiftTests/Tests/BagTest.swift index d2eb927b..a4a16b48 100644 --- a/Tests/RxSwiftTests/Tests/BagTest.swift +++ b/Tests/RxSwiftTests/Tests/BagTest.swift @@ -57,7 +57,7 @@ extension BagTest { numberOfActionsAfter(i, deletionsFromStart: j, createNew: { () -> Disposable in AnonymousDisposable { numberDisposables += 1 } }, - bagAction: { (bag: RxMutableBox>) in disposeAllIn(bag.value); XCTAssertTrue(bag.value.count == i - j) } + bagAction: { (bag: RxMutableBox>) in disposeAll(in: bag.value); XCTAssertTrue(bag.value.count == i - j) } ) XCTAssertTrue(numberForEachActions == i - j) @@ -104,7 +104,7 @@ extension BagTest { numberOfActionsAfter(i, deletionsFromStart: j, createNew: { () -> Disposable in AnonymousDisposable { numberDisposables += 1 } }, - bagAction: { (bag: RxMutableBox>) in disposeAllIn(bag.value); XCTAssertTrue(bag.value.count == i - j) } + bagAction: { (bag: RxMutableBox>) in disposeAll(in: bag.value); XCTAssertTrue(bag.value.count == i - j) } ) XCTAssertTrue(numberForEachActions == i - j) @@ -152,7 +152,7 @@ extension BagTest { bag2.value.on(.next(1)) - disposeAllIn(bag3.value) + disposeAll(in: bag3.value) } XCTAssertEqual(increment1, 50) @@ -177,7 +177,7 @@ extension BagTest { numberOfActionsAfter(100, deletionsFromStart: 0, createNew: { () -> Disposable in AnonymousDisposable { numberDisposables += 1 } }, - bagAction: { (bag: RxMutableBox>) in bag.value.removeAll(); disposeAllIn(bag.value); } + bagAction: { (bag: RxMutableBox>) in bag.value.removeAll(); disposeAll(in: bag.value); } ) XCTAssertTrue(numberForEachActions == 0) diff --git a/Tests/RxSwiftTests/Tests/DisposableTest.swift b/Tests/RxSwiftTests/Tests/DisposableTest.swift index 58d2e3ce..dead2cbe 100644 --- a/Tests/RxSwiftTests/Tests/DisposableTest.swift +++ b/Tests/RxSwiftTests/Tests/DisposableTest.swift @@ -143,7 +143,7 @@ class DisposableTest : RxTest { XCTAssertEqual(compositeDisposable.count, 2) XCTAssertTrue(result1 != nil) - compositeDisposable.removeDisposable(result2!) + compositeDisposable.remove(for: result2!) XCTAssertEqual(numberDisposed, 1) XCTAssertEqual(compositeDisposable.count, 1) diff --git a/Tests/RxSwiftTests/Tests/Observable+ConcurrencyTest.swift b/Tests/RxSwiftTests/Tests/Observable+ConcurrencyTest.swift index 2d0d50f7..5a038a26 100644 --- a/Tests/RxSwiftTests/Tests/Observable+ConcurrencyTest.swift +++ b/Tests/RxSwiftTests/Tests/Observable+ConcurrencyTest.swift @@ -13,7 +13,7 @@ import RxBlocking import RxTests class ObservableConcurrencyTestBase : RxTest { - var lock = Lock() + var lock = NSLock() func performLocked(_ action: () -> Void) { lock.lock() @@ -332,7 +332,7 @@ class ObservableConcurrentSchedulerConcurrencyTest: ObservableConcurrencyTestBas let scheduler = createScheduler() - let condition = Condition() + let condition = NSCondition() var writtenStarted = 0 var writtenEnded = 0 diff --git a/Tests/RxSwiftTests/Tests/Observable+MultipleTest.swift b/Tests/RxSwiftTests/Tests/Observable+MultipleTest.swift index 8f105c3d..b669a745 100644 --- a/Tests/RxSwiftTests/Tests/Observable+MultipleTest.swift +++ b/Tests/RxSwiftTests/Tests/Observable+MultipleTest.swift @@ -3213,7 +3213,7 @@ extension ObservableMultipleTest { ]) let res = scheduler.start { - [e0, e1, e2].combineLatest { $0.reduce(0, combine:+) } + [e0, e1, e2].combineLatest { $0.reduce(0, +) } } XCTAssertEqual(res.events, []) @@ -3236,7 +3236,7 @@ extension ObservableMultipleTest { ]) let res = scheduler.start { - [e0, e1].combineLatest { $0.reduce(0, combine:+) } + [e0, e1].combineLatest { $0.reduce(0, +) } } XCTAssertEqual(res.events, []) @@ -3258,7 +3258,7 @@ extension ObservableMultipleTest { ]) let res = scheduler.start { - [e0, e1].combineLatest { $0.reduce(0, combine:+) } + [e0, e1].combineLatest { $0.reduce(0, +) } } XCTAssertEqual(res.events, []) @@ -3282,7 +3282,7 @@ extension ObservableMultipleTest { ]) let res = scheduler.start { - ([e0, e1] as [TestableObservable]).combineLatest { $0.reduce(0, combine:+) } + ([e0, e1] as [TestableObservable]).combineLatest { $0.reduce(0, +) } } XCTAssertEqual(res.events, [ @@ -3309,7 +3309,7 @@ extension ObservableMultipleTest { ]) let res = scheduler.start { - [e0, e1].combineLatest { $0.reduce(0, combine:+) } + [e0, e1].combineLatest { $0.reduce(0, +) } } XCTAssertEqual(res.events, [ @@ -3335,7 +3335,7 @@ extension ObservableMultipleTest { ]) let res = scheduler.start { - [e0, e1].combineLatest { $0.reduce(0, combine:+) } + [e0, e1].combineLatest { $0.reduce(0, +) } } XCTAssertEqual(res.events, [ @@ -3361,7 +3361,7 @@ extension ObservableMultipleTest { ]) let res = scheduler.start { - [e0, e1].combineLatest { $0.reduce(0, combine:+) } + [e0, e1].combineLatest { $0.reduce(0, +) } } XCTAssertEqual(res.events, [ @@ -3386,7 +3386,7 @@ extension ObservableMultipleTest { ]) let res = scheduler.start { - [e0, e1].combineLatest { $0.reduce(0, combine:+) } + [e0, e1].combineLatest { $0.reduce(0, +) } } XCTAssertEqual(res.events, [ @@ -3410,7 +3410,7 @@ extension ObservableMultipleTest { ]) let res = scheduler.start { - [e0, e1].combineLatest { $0.reduce(0, combine:+) } + [e0, e1].combineLatest { $0.reduce(0, +) } } XCTAssertEqual(res.events, [ @@ -3436,7 +3436,7 @@ extension ObservableMultipleTest { ]) let res = scheduler.start { - [e0, e1].combineLatest { $0.reduce(0, combine:+) } + [e0, e1].combineLatest { $0.reduce(0, +) } } XCTAssertEqual(res.events, [ @@ -3462,7 +3462,7 @@ extension ObservableMultipleTest { ]) let res = scheduler.start { - [e0, e1].combineLatest { $0.reduce(0, combine:+) } + [e0, e1].combineLatest { $0.reduce(0, +) } } XCTAssertEqual(res.events, [ @@ -3493,7 +3493,7 @@ extension ObservableMultipleTest { ]) let res = scheduler.start { - [e0, e1].combineLatest { $0.reduce(0, combine:+) } + [e0, e1].combineLatest { $0.reduce(0, +) } } XCTAssertEqual(res.events, [ @@ -3527,7 +3527,7 @@ extension ObservableMultipleTest { ]) let res = scheduler.start { - [e0, e1].combineLatest { $0.reduce(0, combine:+) } + [e0, e1].combineLatest { $0.reduce(0, +) } } XCTAssertEqual(res.events, [ @@ -3558,7 +3558,7 @@ extension ObservableMultipleTest { ]) let res = scheduler.start { - [e0, e1].combineLatest { $0.reduce(0, combine:+) } + [e0, e1].combineLatest { $0.reduce(0, +) } } XCTAssertEqual(res.events, [ @@ -3587,7 +3587,7 @@ extension ObservableMultipleTest { ]) let res = scheduler.start { - [e0, e1].combineLatest { $0.reduce(0, combine:+) } + [e0, e1].combineLatest { $0.reduce(0, +) } } XCTAssertEqual(res.events, [ @@ -3682,7 +3682,7 @@ extension ObservableMultipleTest { ]) let res = scheduler.start { - [e0, e1, e2].combineLatest { $0.reduce(0, combine:+) } + [e0, e1, e2].combineLatest { $0.reduce(0, +) } } XCTAssertEqual(res.events, [ diff --git a/Tests/RxSwiftTests/Tests/Observable+SingleTest.swift b/Tests/RxSwiftTests/Tests/Observable+SingleTest.swift index a4f7d9bd..e7d04c21 100644 --- a/Tests/RxSwiftTests/Tests/Observable+SingleTest.swift +++ b/Tests/RxSwiftTests/Tests/Observable+SingleTest.swift @@ -665,7 +665,7 @@ extension ObservableSingleTest { XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) - XCTAssertTrue((recordedError as! AnyObject) === testError) + XCTAssertTrue((recordedError as AnyObject) === testError) XCTAssertEqual(numberOfTimesInvoked, 1) } diff --git a/Tests/RxSwiftTests/Tests/SchedulerTests.swift b/Tests/RxSwiftTests/Tests/SchedulerTests.swift index ce35afe6..50a4de4e 100644 --- a/Tests/RxSwiftTests/Tests/SchedulerTests.swift +++ b/Tests/RxSwiftTests/Tests/SchedulerTests.swift @@ -62,7 +62,7 @@ extension ConcurrentDispatchQueueSchedulerTests { } disposable.dispose() - DispatchQueue.main.after(when: .now() + .milliseconds(200)) { + DispatchQueue.main.asyncAfter (deadline: .now() + .milliseconds(200)) { expectScheduling.fulfill() } @@ -112,7 +112,7 @@ extension ConcurrentDispatchQueueSchedulerTests { disposable.dispose() - DispatchQueue.main.after(when: .now() + .milliseconds(300)) { + DispatchQueue.main.asyncAfter (deadline: .now() + .milliseconds(300)) { expectScheduling.fulfill() } diff --git a/Tests/RxSwiftTests/Tests/SubjectConcurrencyTest.swift b/Tests/RxSwiftTests/Tests/SubjectConcurrencyTest.swift index 12868d77..d25edabe 100644 --- a/Tests/RxSwiftTests/Tests/SubjectConcurrencyTest.swift +++ b/Tests/RxSwiftTests/Tests/SubjectConcurrencyTest.swift @@ -49,7 +49,7 @@ extension SubjectConcurrencyTest { if state == 0 { state = 1 - DispatchQueue.global(attributes: DispatchQueue.GlobalAttributes.qosUserInitiated).async { + DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { o.value.on(.next(1)) } diff --git a/Tests/RxTest.swift b/Tests/RxTest.swift index 9f7a761b..b88edb84 100644 --- a/Tests/RxTest.swift +++ b/Tests/RxTest.swift @@ -83,7 +83,7 @@ extension RxTest { func setUpActions(){ #if TRACE_RESOURCES self.startResourceCount = resourceCount - registerMallocHooks() + //registerMallocHooks() (startNumberOfAllocatedBytes, startNumberOfAllocations) = getMemoryInfo() #endif } diff --git a/Tests/Tests/XCTest+AllTests.swift b/Tests/Tests/XCTest+AllTests.swift index 15c8f5d2..4954b5c0 100644 --- a/Tests/Tests/XCTest+AllTests.swift +++ b/Tests/Tests/XCTest+AllTests.swift @@ -65,7 +65,7 @@ func XCTAssertEqual(_ lhs: [T], _ rhs: [T], _ comparison: (T, T) -> Bool) { func doOnBackgroundThread(_ action: () -> ()) { - DispatchQueue.global(attributes: DispatchQueue.GlobalAttributes.qosDefault).async(execute: action) + DispatchQueue.global(qos: .default).async(execute: action) } func doOnMainThread(_ action: () -> ()) { From 58e427b045b4f2823581ce89e9082bb2de19f0a4 Mon Sep 17 00:00:00 2001 From: Krunoslav Zaher Date: Thu, 4 Aug 2016 11:53:19 +0200 Subject: [PATCH 15/52] Fixes playgrounds compilation issues. --- .../Contents.swift | 6 +++--- .../Contents.swift | 2 +- .../Contents.swift | 2 +- .../Contents.swift | 8 ++++---- .../Contents.swift | 2 +- Rx.playground/Sources/SupportCode.swift | 10 +++++----- 6 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Rx.playground/Pages/Connectable_Operators.xcplaygroundpage/Contents.swift b/Rx.playground/Pages/Connectable_Operators.xcplaygroundpage/Contents.swift index d7637db0..28587da8 100644 --- a/Rx.playground/Pages/Connectable_Operators.xcplaygroundpage/Contents.swift +++ b/Rx.playground/Pages/Connectable_Operators.xcplaygroundpage/Contents.swift @@ -49,7 +49,7 @@ func sampleWithPublish() { _ = intSequence .subscribeNext { print("Subscription 1:, Event: \($0)") } - delay(2) { intSequence.connect() } + delay(2) { _ = intSequence.connect() } delay(4) { _ = intSequence @@ -81,7 +81,7 @@ func sampleWithReplayBuffer() { _ = intSequence .subscribeNext { print("Subscription 1:, Event: \($0)") } - delay(2) { intSequence.connect() } + delay(2) { _ = intSequence.connect() } delay(4) { _ = intSequence @@ -115,7 +115,7 @@ func sampleWithMulticast() { _ = intSequence .subscribeNext { print("\tSubscription 1:, Event: \($0)") } - delay(2) { intSequence.connect() } + delay(2) { _ = intSequence.connect() } delay(4) { _ = intSequence diff --git a/Rx.playground/Pages/Creating_and_Subscribing_to_Observables.xcplaygroundpage/Contents.swift b/Rx.playground/Pages/Creating_and_Subscribing_to_Observables.xcplaygroundpage/Contents.swift index 7f751cf0..0df97e9b 100644 --- a/Rx.playground/Pages/Creating_and_Subscribing_to_Observables.xcplaygroundpage/Contents.swift +++ b/Rx.playground/Pages/Creating_and_Subscribing_to_Observables.xcplaygroundpage/Contents.swift @@ -190,7 +190,7 @@ example("deferred") { example("error") { let disposeBag = DisposeBag() - Observable.error(Error.test) + Observable.error(TestError.test) .subscribe { print($0) } .addDisposableTo(disposeBag) } diff --git a/Rx.playground/Pages/Debugging_Operators.xcplaygroundpage/Contents.swift b/Rx.playground/Pages/Debugging_Operators.xcplaygroundpage/Contents.swift index fdde6b68..4165dad9 100644 --- a/Rx.playground/Pages/Debugging_Operators.xcplaygroundpage/Contents.swift +++ b/Rx.playground/Pages/Debugging_Operators.xcplaygroundpage/Contents.swift @@ -24,7 +24,7 @@ example("debug") { observer.onNext("🍊") if count < 5 { - observer.onError(Error.Test) + observer.onError(TestError.test) print("Error encountered") count += 1 } diff --git a/Rx.playground/Pages/Error_Handling_Operators.xcplaygroundpage/Contents.swift b/Rx.playground/Pages/Error_Handling_Operators.xcplaygroundpage/Contents.swift index 0383aa15..37c6b6d4 100644 --- a/Rx.playground/Pages/Error_Handling_Operators.xcplaygroundpage/Contents.swift +++ b/Rx.playground/Pages/Error_Handling_Operators.xcplaygroundpage/Contents.swift @@ -29,7 +29,7 @@ example("catchErrorJustReturn") { sequenceThatFails.onNext("😨") sequenceThatFails.onNext("😡") sequenceThatFails.onNext("🔴") - sequenceThatFails.onError(Error.Test) + sequenceThatFails.onError(TestError.test) } /*: ---- @@ -55,7 +55,7 @@ example("catchError") { sequenceThatFails.onNext("😨") sequenceThatFails.onNext("😡") sequenceThatFails.onNext("🔴") - sequenceThatFails.onError(Error.Test) + sequenceThatFails.onError(TestError.test) recoverySequence.onNext("😊") } @@ -75,7 +75,7 @@ example("retry") { observer.onNext("🍊") if count == 1 { - observer.onError(Error.Test) + observer.onError(TestError.test) print("Error encountered") count += 1 } @@ -109,7 +109,7 @@ example("retry maxAttemptCount") { observer.onNext("🍊") if count < 5 { - observer.onError(Error.Test) + observer.onError(TestError.test) print("Error encountered") count += 1 } diff --git a/Rx.playground/Pages/Working_with_Subjects.xcplaygroundpage/Contents.swift b/Rx.playground/Pages/Working_with_Subjects.xcplaygroundpage/Contents.swift index 7d8e4da2..b61ffd75 100644 --- a/Rx.playground/Pages/Working_with_Subjects.xcplaygroundpage/Contents.swift +++ b/Rx.playground/Pages/Working_with_Subjects.xcplaygroundpage/Contents.swift @@ -18,7 +18,7 @@ extension ObservableType { Add observer with `id` and print each emitted event. - parameter id: an identifier for the subscription. */ - func addObserver(id: String) -> Disposable { + func addObserver(_ id: String) -> Disposable { return subscribe { print("Subscription:", id, "Event:", $0) } } diff --git a/Rx.playground/Sources/SupportCode.swift b/Rx.playground/Sources/SupportCode.swift index 298f20e7..e830a8f7 100644 --- a/Rx.playground/Sources/SupportCode.swift +++ b/Rx.playground/Sources/SupportCode.swift @@ -5,16 +5,16 @@ import Foundation - parameter description: example description - parameter action: `Void` closure */ -public func example(description: String, action: @noescape(Void) -> Void) { - printExampleHeader(description: description) +public func example(_ description: String, action: @noescape(Void) -> Void) { + printExampleHeader(description) action() } -public func printExampleHeader(description: String) { +public func printExampleHeader(_ description: String) { print("\n--- \(description) example ---") } -public enum Error: Swift.Error { +public enum TestError: Swift.Error { case test } @@ -24,7 +24,7 @@ public enum Error: Swift.Error { - parameter delay: time in seconds to wait before executing `closure` - parameter closure: `Void` closure */ -public func delay(delay: Double, closure: (Void) -> Void) { +public func delay(_ delay: Double, closure: (Void) -> Void) { let delayTime = DispatchTime.now() + DispatchTimeInterval.seconds(Int(delay)) DispatchQueue.main.asyncAfter(deadline: delayTime) { From 0b1856d43ed9bc20e9005e9e32b0b71f02036a54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Burojevi=C4=87?= Date: Sat, 6 Aug 2016 19:44:02 +0200 Subject: [PATCH 16/52] Fixes typo in Getting Started --- Documentation/GettingStarted.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/GettingStarted.md b/Documentation/GettingStarted.md index 30139d78..4d09961f 100644 --- a/Documentation/GettingStarted.md +++ b/Documentation/GettingStarted.md @@ -714,7 +714,7 @@ If you are unsure how exactly some of the operators work, [playgrounds](../Rx.pl ## Error handling -The are two error mechanisms. +There are two error mechanisms. ### Asynchronous error handling mechanism in observables From 208a84db0fb7c02f72d81e0ffcf5f511a5de8e82 Mon Sep 17 00:00:00 2001 From: Junior B Date: Sun, 7 Aug 2016 01:33:37 +0200 Subject: [PATCH 17/52] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2e55424d..b65cb038 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ KVO observing, async operations and streams are all unified under [abstraction o ###### ... interact -* All of this is great, but it would be nice to talk with other people using RxSwift and exchange experiences.
[![Slack channel](http://slack.rxswift.org/badge.svg)](http://slack.rxswift.org) [Join Slack Channel](http://slack.rxswift.org/) +* All of this is great, but it would be nice to talk with other people using RxSwift and exchange experiences.
[![Slack channel](http://rxswift-slack.herokuapp.com/badge.svg)](http://slack.rxswift.org) [Join Slack Channel](http://rxswift-slack.herokuapp.com) * Report a problem using the library. [Open an Issue With Bug Template](ISSUE_TEMPLATE.md) * Request a new feature. [Open an Issue With Feature Request Template](Documentation/NewFeatureRequestTemplate.md) From e2c3330d619dfd18cebffa23fb3ed235ac1b8ebb Mon Sep 17 00:00:00 2001 From: Krunoslav Zaher Date: Sun, 7 Aug 2016 15:12:01 +0200 Subject: [PATCH 18/52] Fixes default datasources implementation. #825 --- RxCocoa/Common/DelegateProxyType.swift | 8 ++++---- RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift | 5 +++++ RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift | 4 ++-- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/RxCocoa/Common/DelegateProxyType.swift b/RxCocoa/Common/DelegateProxyType.swift index 82cd79bb..d42c01df 100644 --- a/RxCocoa/Common/DelegateProxyType.swift +++ b/RxCocoa/Common/DelegateProxyType.swift @@ -178,14 +178,14 @@ extension DelegateProxyType { let maybeProxy = Self.assignedProxyFor(object) as? Self let proxy: Self - if maybeProxy == nil { + if let existingProxy = maybeProxy { + proxy = existingProxy + } + else { proxy = Self.createProxyForObject(object) as! Self Self.assignProxy(proxy, toObject: object) assert(Self.assignedProxyFor(object) === proxy) } - else { - proxy = maybeProxy! - } let currentDelegate: AnyObject? = Self.currentDelegateFor(object) diff --git a/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift b/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift index eaa3f2ba..5614450c 100644 --- a/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift +++ b/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift @@ -19,6 +19,11 @@ let collectionViewDataSourceNotSet = CollectionViewDataSourceNotSet() class CollectionViewDataSourceNotSet : NSObject , UICollectionViewDataSource { + + func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { + return 0 + } + func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { rxAbstractMethodWithMessage(dataSourceNotSet) } diff --git a/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift b/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift index 30d4011a..6eaf319c 100644 --- a/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift +++ b/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift @@ -20,7 +20,7 @@ class TableViewDataSourceNotSet : NSObject , UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { - rxAbstractMethodWithMessage(dataSourceNotSet) + return 0 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { @@ -63,7 +63,7 @@ public class RxTableViewDataSourceProxy Required delegate method implementation. */ public func numberOfSectionsInTableView(tableView: UITableView) -> Int { - return (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).numberOfSectionsInTableView?(tableView) ?? 1 + return (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).numberOfSectionsInTableView?(tableView) ?? 0 } /** From 7b6a244f450ae7c40801f2cb21bcf5afd7b8d117 Mon Sep 17 00:00:00 2001 From: Krunoslav Zaher Date: Sun, 7 Aug 2016 15:23:17 +0200 Subject: [PATCH 19/52] Fixes problem with data sources. --- Documentation/Schedulers.md | 2 +- RxCocoa/Common/DelegateProxyType.swift | 8 ++++---- .../iOS/Proxies/RxCollectionViewDataSourceProxy.swift | 4 +++- RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift | 9 +++++---- 4 files changed, 13 insertions(+), 10 deletions(-) diff --git a/Documentation/Schedulers.md b/Documentation/Schedulers.md index 6dbe7cc3..331f5e39 100644 --- a/Documentation/Schedulers.md +++ b/Documentation/Schedulers.md @@ -13,7 +13,7 @@ There are two main operators that work with schedulers, `observeOn` and `subscri If you want to perform work on a different scheduler just use `observeOn(scheduler)` operator. -You would usually use `observeOn` a lot more often then `subscribeOn`. +You would usually use `observeOn` a lot more often than `subscribeOn`. In case `observeOn` isn't explicitly specified, work will be performed on whichever thread/scheduler elements are generated. diff --git a/RxCocoa/Common/DelegateProxyType.swift b/RxCocoa/Common/DelegateProxyType.swift index eded49a1..f41782a6 100644 --- a/RxCocoa/Common/DelegateProxyType.swift +++ b/RxCocoa/Common/DelegateProxyType.swift @@ -178,14 +178,14 @@ extension DelegateProxyType { let maybeProxy = Self.assignedProxyFor(object) as? Self let proxy: Self - if maybeProxy == nil { + if let existingProxy = maybeProxy { + proxy = existingProxy + } + else { proxy = Self.createProxyForObject(object) as! Self Self.assignProxy(proxy, toObject: object) assert(Self.assignedProxyFor(object) === proxy) } - else { - proxy = maybeProxy! - } let currentDelegate: AnyObject? = Self.currentDelegateFor(object) diff --git a/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift b/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift index 452a14c6..e34c20db 100644 --- a/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift +++ b/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift @@ -19,8 +19,10 @@ let collectionViewDataSourceNotSet = CollectionViewDataSourceNotSet() class CollectionViewDataSourceNotSet : NSObject , UICollectionViewDataSource { + + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { - rxAbstractMethodWithMessage(dataSourceNotSet) + return 0 } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: diff --git a/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift b/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift index 75e8033a..558008ea 100644 --- a/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift +++ b/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift @@ -19,8 +19,9 @@ let tableViewDataSourceNotSet = TableViewDataSourceNotSet() class TableViewDataSourceNotSet : NSObject , UITableViewDataSource { - func numberOfSections(in tableView: UITableView) -> Int { - rxAbstractMethodWithMessage(dataSourceNotSet) + + func numberOfSectionsInTableView(tableView: UITableView) -> Int { + return 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { @@ -62,8 +63,8 @@ public class RxTableViewDataSourceProxy /** Required delegate method implementation. */ - public func numberOfSections(in tableView: UITableView) -> Int { - return (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).numberOfSections?(in: tableView) ?? 1 + public func numberOfSectionsInTableView(tableView: UITableView) -> Int { + return (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).numberOfSections?(in: tableView) ?? 0 } /** From 10b0d39e0564c36e334b0410ef9f663f4ffdc8cd Mon Sep 17 00:00:00 2001 From: Krunoslav Zaher Date: Sun, 7 Aug 2016 16:04:47 +0200 Subject: [PATCH 20/52] Fixes warnings. --- .../iOS/Proxies/RxTableViewDataSourceProxy.swift | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift b/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift index 558008ea..c7df9a57 100644 --- a/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift +++ b/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift @@ -20,12 +20,8 @@ class TableViewDataSourceNotSet : NSObject , UITableViewDataSource { - func numberOfSectionsInTableView(tableView: UITableView) -> Int { - return 0 - } - func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - rxAbstractMethodWithMessage(dataSourceNotSet) + return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { @@ -60,13 +56,6 @@ public class RxTableViewDataSourceProxy // MARK: delegate - /** - Required delegate method implementation. - */ - public func numberOfSectionsInTableView(tableView: UITableView) -> Int { - return (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).numberOfSections?(in: tableView) ?? 0 - } - /** Required delegate method implementation. */ From 1b0e0a3c88f23c9fecab2bae457a9fde2c7c0a4e Mon Sep 17 00:00:00 2001 From: Krunoslav Zaher Date: Sun, 7 Aug 2016 16:12:16 +0200 Subject: [PATCH 21/52] Updates RxDataSources. --- .../RxDataSources/DataSources/DataSources.swift | 4 ++-- .../RxDataSources/DataSources/Differentiator.swift | 2 +- .../DataSources/TableViewSectionedDataSource.swift | 13 +++++++++---- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/RxExample/RxDataSources/DataSources/DataSources.swift b/RxExample/RxDataSources/DataSources/DataSources.swift index 0d560711..7a7c7253 100644 --- a/RxExample/RxDataSources/DataSources/DataSources.swift +++ b/RxExample/RxDataSources/DataSources/DataSources.swift @@ -8,7 +8,7 @@ import Foundation -enum RxDataSourceError : Swift.Error { +enum RxDataSourceError : Error { case unwrappingOptional case preconditionFailed(message: String) } @@ -22,7 +22,7 @@ func rxPrecondition(_ condition: Bool, _ message: @autoclosure() -> String) thro throw RxDataSourceError.preconditionFailed(message: message()) } -func rxDebugFatalError(_ error: Swift.Error) { +func rxDebugFatalError(_ error: Error) { rxDebugFatalError("\(error)") } diff --git a/RxExample/RxDataSources/DataSources/Differentiator.swift b/RxExample/RxDataSources/DataSources/Differentiator.swift index 79e33bb5..9dcf13df 100644 --- a/RxExample/RxDataSources/DataSources/Differentiator.swift +++ b/RxExample/RxDataSources/DataSources/Differentiator.swift @@ -9,7 +9,7 @@ import Foundation public enum DifferentiatorError - : Swift.Error + : Error , CustomDebugStringConvertible { case duplicateItem(item: Any) case duplicateSection(section: Any) diff --git a/RxExample/RxDataSources/DataSources/TableViewSectionedDataSource.swift b/RxExample/RxDataSources/DataSources/TableViewSectionedDataSource.swift index 29829182..856dfd2b 100644 --- a/RxExample/RxDataSources/DataSources/TableViewSectionedDataSource.swift +++ b/RxExample/RxDataSources/DataSources/TableViewSectionedDataSource.swift @@ -72,7 +72,8 @@ public class _TableViewSectionedDataSource public func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return _rx_tableView(tableView, canMoveRowAtIndexPath: indexPath) } - + + #if os(iOS) func _sectionIndexTitlesForTableView(_ tableView: UITableView) -> [String]? { return nil } @@ -80,7 +81,7 @@ public class _TableViewSectionedDataSource public func sectionIndexTitles(for tableView: UITableView) -> [String]? { return _sectionIndexTitlesForTableView(tableView) } - + func _rx_tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { return 0 } @@ -88,6 +89,7 @@ public class _TableViewSectionedDataSource public func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { return _rx_tableView(tableView, sectionForSectionIndexTitle: title, atIndex: index) } + #endif func _rx_tableView(_ tableView: UITableView, moveRowAtIndexPath sourceIndexPath: IndexPath, toIndexPath destinationIndexPath: IndexPath) { } @@ -195,6 +197,7 @@ public class RxTableViewSectionedDataSource public var rowAnimation: UITableViewRowAnimation = .automatic + #if os(iOS) public var sectionIndexTitles: ((RxTableViewSectionedDataSource) -> [String]?)? { didSet { #if DEBUG @@ -209,6 +212,7 @@ public class RxTableViewSectionedDataSource #endif } } + #endif public override init() { super.init() @@ -264,7 +268,8 @@ public class RxTableViewSectionedDataSource override func _rx_tableView(_ tableView: UITableView, moveRowAtIndexPath sourceIndexPath: IndexPath, toIndexPath destinationIndexPath: IndexPath) { self._sectionModels.moveFromSourceIndexPath(sourceIndexPath, destinationIndexPath: destinationIndexPath) } - + + #if os(iOS) override func _sectionIndexTitlesForTableView(_ tableView: UITableView) -> [String]? { guard let titles = sectionIndexTitles?(self) else { return super._sectionIndexTitlesForTableView(tableView) @@ -280,5 +285,5 @@ public class RxTableViewSectionedDataSource return section } - + #endif } From afd40f5d8b3042c976a4ff50110ff863bc7a29cd Mon Sep 17 00:00:00 2001 From: Krunoslav Zaher Date: Sun, 7 Aug 2016 16:48:25 +0200 Subject: [PATCH 22/52] Modernizes UICollectionView extensions. --- RxCocoa/iOS/UICollectionView+Rx.swift | 138 +++++++++++++++++ RxCocoa/iOS/UITableView+Rx.swift | 145 +++++++++++++++++- ...tHubSearchRepositoriesViewController.swift | 2 +- ...SimpleTableViewExampleViewController.swift | 2 +- ...leViewExampleSectionedViewController.swift | 2 +- .../PartialUpdatesViewController.swift | 4 +- ...iewWithEditingCommandsViewController.swift | 2 +- .../Views/WikipediaSearchViewController.swift | 2 +- .../UICollectionView+RxTests.swift | 20 +-- Tests/RxCocoaTests/UITableView+RxTests.swift | 20 +-- 10 files changed, 309 insertions(+), 28 deletions(-) diff --git a/RxCocoa/iOS/UICollectionView+Rx.swift b/RxCocoa/iOS/UICollectionView+Rx.swift index 1fd54628..eba9f981 100644 --- a/RxCocoa/iOS/UICollectionView+Rx.swift +++ b/RxCocoa/iOS/UICollectionView+Rx.swift @@ -42,6 +42,7 @@ extension UICollectionView { } .addDisposableTo(disposeBag) */ + @available(*, deprecated, renamed: "rx_items(source:cellFactory:)") public func rx_itemsWithCellFactory (_ source: O) -> (cellFactory: (UICollectionView, Int, S.Iterator.Element) -> UICollectionViewCell) @@ -56,6 +57,41 @@ extension UICollectionView { /** Binds sequences of elements to collection view items. + - 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([ + 1, + 2, + 3 + ]) + + items + .bindTo(collectionView.rx_items) { (collectionView, row, element) in + let indexPath = IndexPath(forItem: row, inSection: 0) + let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! NumberCell + cell.value?.text = "\(element) @ \(row)" + return cell + } + .addDisposableTo(disposeBag) + */ + public func rx_items + (source: O) + -> (cellFactory: (UICollectionView, Int, S.Iterator.Element) -> UICollectionViewCell) + -> Disposable { + return { cellFactory in + let dataSource = RxCollectionViewReactiveArrayDataSourceSequenceWrapper(cellFactory: cellFactory) + return self.rx_items(dataSource: dataSource)(source: source) + } + + } + + /** + Binds sequences of elements to collection view items. + - parameter cellIdentifier: Identifier used to dequeue cells. - parameter source: Observable sequence of items. - parameter configureCell: Transform between sequence elements and view cells. @@ -76,6 +112,7 @@ extension UICollectionView { } .addDisposableTo(disposeBag) */ + @available(*, deprecated, renamed: "rx_items(cellIdentifier:cellType:source:configureCell:)") public func rx_itemsWithCellIdentifier (_ cellIdentifier: String, cellType: Cell.Type = Cell.self) -> (source: O) @@ -94,6 +131,49 @@ extension UICollectionView { } } } + + /** + Binds sequences of elements to collection view items. + + - 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([ + 1, + 2, + 3 + ]) + + items + .bindTo(collectionView.rx_items(cellIdentifier: "Cell", cellType: NumberCell.self)) { (row, element, cell) in + cell.value?.text = "\(element) @ \(row)" + } + .addDisposableTo(disposeBag) + */ + public func rx_items + (cellIdentifier: String, cellType: Cell.Type = Cell.self) + -> (source: O) + -> (configureCell: (Int, S.Iterator.Element, Cell) -> Void) + -> Disposable { + return { source in + return { configureCell in + let dataSource = RxCollectionViewReactiveArrayDataSourceSequenceWrapper { (cv, i, item) in + let indexPath = IndexPath(item: i, section: 0) + let cell = cv.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! Cell + configureCell(i, item, cell) + return cell + } + + return self.rx_items(dataSource: dataSource)(source: source) + } + } + } + /** Binds sequences of elements to collection view items using a custom reactive data used to perform the transformation. @@ -134,6 +214,7 @@ extension UICollectionView { .bindTo(collectionView.rx_itemsWithDataSource(dataSource)) .addDisposableTo(disposeBag) */ + @available(*, deprecated, renamed: "rx_items(dataSource:source:)") public func rx_itemsWithDataSource< DataSource: RxCollectionViewDataSourceType & UICollectionViewDataSource, O: ObservableType where DataSource.Element == O.E @@ -151,6 +232,63 @@ extension UICollectionView { } } } + + /** + Binds sequences of elements to collection view items using a custom reactive data used to perform the transformation. + + - 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. + + Example + + let dataSource = RxCollectionViewSectionedReloadDataSource>() + + let items = Observable.just([ + SectionModel(model: "First section", items: [ + 1.0, + 2.0, + 3.0 + ]), + SectionModel(model: "Second section", items: [ + 1.0, + 2.0, + 3.0 + ]), + SectionModel(model: "Third section", items: [ + 1.0, + 2.0, + 3.0 + ]) + ]) + + dataSource.configureCell = { (dataSource, cv, indexPath, element) in + let cell = cv.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! NumberCell + cell.value?.text = "\(element) @ row \(indexPath.row)" + return cell + } + + items + .bindTo(collectionView.rx_items(dataSource: dataSource)) + .addDisposableTo(disposeBag) + */ + public func rx_items< + DataSource: RxCollectionViewDataSourceType & UICollectionViewDataSource, + O: ObservableType where DataSource.Element == O.E + > + (dataSource: DataSource) + -> (source: O) + -> Disposable { + return { source in + + return source.subscribeProxyDataSourceForObject(self, dataSource: dataSource, retainDataSource: true) { [weak self] (_: RxCollectionViewDataSourceProxy, event) -> Void in + guard let collectionView = self else { + return + } + dataSource.collectionView(collectionView, observedEvent: event) + } + } + } } extension UICollectionView { diff --git a/RxCocoa/iOS/UITableView+Rx.swift b/RxCocoa/iOS/UITableView+Rx.swift index 0eea50e5..0c55d209 100644 --- a/RxCocoa/iOS/UITableView+Rx.swift +++ b/RxCocoa/iOS/UITableView+Rx.swift @@ -42,6 +42,7 @@ extension UITableView { .addDisposableTo(disposeBag) */ + @available(*, deprecated, renamed: "rx_items(source:cellFactory:)") public func rx_itemsWithCellFactory (_ source: O) -> (cellFactory: (UITableView, Int, S.Iterator.Element) -> UITableViewCell) @@ -49,13 +50,48 @@ extension UITableView { return { cellFactory in let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper(cellFactory: cellFactory) - return self.rx_itemsWithDataSource(dataSource)(source: source) + return self.rx_items(dataSource: dataSource)(source: source) } } /** 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 + .bindTo(tableView.rx_items) { (tableView, row, element) in + let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! + cell.textLabel?.text = "\(element) @ row \(row)" + return cell + } + .addDisposableTo(disposeBag) + + */ + public func rx_items + (_ source: O) + -> (cellFactory: (UITableView, Int, S.Iterator.Element) -> UITableViewCell) + -> Disposable { + return { cellFactory in + let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper(cellFactory: cellFactory) + + return self.rx_items(dataSource: dataSource)(source: 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. @@ -76,6 +112,7 @@ extension UITableView { } .addDisposableTo(disposeBag) */ + @available(*, deprecated, renamed: "rx_items(cellIdentifier:cellType:source:configureCell:)") public func rx_itemsWithCellIdentifier (_ cellIdentifier: String, cellType: Cell.Type = Cell.self) -> (source: O) @@ -93,6 +130,48 @@ extension UITableView { } } } + + /** + 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 + .bindTo(tableView.rx_items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { (row, element, cell) in + cell.textLabel?.text = "\(element) @ row \(row)" + } + .addDisposableTo(disposeBag) + */ + public func rx_items + (cellIdentifier: String, cellType: Cell.Type = Cell.self) + -> (source: O) + -> (configureCell: (Int, S.Iterator.Element, Cell) -> Void) + -> Disposable { + return { source in + return { configureCell in + let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper { (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.rx_items(dataSource: dataSource)(source: source) + } + } + } + /** Binds sequences of elements to table view rows using a custom reactive data used to perform the transformation. @@ -137,6 +216,7 @@ extension UITableView { .bindTo(tableView.rx_itemsWithDataSource(dataSource)) .addDisposableTo(disposeBag) */ + @available(*, deprecated, renamed: "rx_items(dataSource:source:)") public func rx_itemsWithDataSource< DataSource: RxTableViewDataSourceType & UITableViewDataSource, O: ObservableType where DataSource.Element == O.E @@ -154,6 +234,69 @@ extension UITableView { } } } + + + /** + 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 sucessfully, 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. + + Example + + let dataSource = RxTableViewSectionedReloadDataSource>() + + let items = Observable.just([ + SectionModel(model: "First section", items: [ + 1.0, + 2.0, + 3.0 + ]), + SectionModel(model: "Second section", items: [ + 1.0, + 2.0, + 3.0 + ]), + SectionModel(model: "Third section", items: [ + 1.0, + 2.0, + 3.0 + ]) + ]) + + dataSource.configureCell = { (dataSource, tv, indexPath, element) in + let cell = tv.dequeueReusableCellWithIdentifier("Cell")! + cell.textLabel?.text = "\(element) @ row \(indexPath.row)" + return cell + } + + items + .bindTo(tableView.rx_items(dataSource: dataSource)) + .addDisposableTo(disposeBag) + */ + public func rx_items< + DataSource: RxTableViewDataSourceType & UITableViewDataSource, + O: ObservableType where DataSource.Element == O.E + > + (dataSource: DataSource) + -> (source: O) + -> Disposable { + return { source in + // There needs to be a strong retaining here because + return source.subscribeProxyDataSourceForObject(self, dataSource: dataSource, retainDataSource: true) { [weak self] (_: RxTableViewDataSourceProxy, event) -> Void in + guard let tableView = self else { + return + } + dataSource.tableView(tableView, observedEvent: event) + } + } + } + } extension UITableView { diff --git a/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesViewController.swift b/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesViewController.swift index 23d1e444..b0647513 100644 --- a/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesViewController.swift +++ b/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesViewController.swift @@ -74,7 +74,7 @@ class GitHubSearchRepositoriesViewController: ViewController, UITableViewDelegat searchResult .map { [SectionModel(model: "Repositories", items: $0.repositories)] } - .drive(tableView.rx_itemsWithDataSource(dataSource)) + .drive(tableView.rx_items(dataSource: dataSource)) .addDisposableTo(disposeBag) searchResult diff --git a/RxExample/RxExample/Examples/SimpleTableViewExample/SimpleTableViewExampleViewController.swift b/RxExample/RxExample/Examples/SimpleTableViewExample/SimpleTableViewExampleViewController.swift index 6396f56f..2e18bd69 100644 --- a/RxExample/RxExample/Examples/SimpleTableViewExample/SimpleTableViewExampleViewController.swift +++ b/RxExample/RxExample/Examples/SimpleTableViewExample/SimpleTableViewExampleViewController.swift @@ -26,7 +26,7 @@ class SimpleTableViewExampleViewController : ViewController { ]) items - .bindTo(tableView.rx_itemsWithCellIdentifier("Cell", cellType: UITableViewCell.self)) { (row, element, cell) in + .bindTo(tableView.rx_items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { (row, element, cell) in cell.textLabel?.text = "\(element) @ row \(row)" } .addDisposableTo(disposeBag) diff --git a/RxExample/RxExample/Examples/SimpleTableViewExampleSectioned/SimpleTableViewExampleSectionedViewController.swift b/RxExample/RxExample/Examples/SimpleTableViewExampleSectioned/SimpleTableViewExampleSectionedViewController.swift index 6c627314..720b9fbe 100644 --- a/RxExample/RxExample/Examples/SimpleTableViewExampleSectioned/SimpleTableViewExampleSectionedViewController.swift +++ b/RxExample/RxExample/Examples/SimpleTableViewExampleSectioned/SimpleTableViewExampleSectionedViewController.swift @@ -50,7 +50,7 @@ class SimpleTableViewExampleSectionedViewController } items - .bindTo(tableView.rx_itemsWithDataSource(dataSource)) + .bindTo(tableView.rx_items(dataSource: dataSource)) .addDisposableTo(disposeBag) tableView diff --git a/RxExample/RxExample/Examples/TableViewPartialUpdates/PartialUpdatesViewController.swift b/RxExample/RxExample/Examples/TableViewPartialUpdates/PartialUpdatesViewController.swift index ecf64e41..03449af5 100644 --- a/RxExample/RxExample/Examples/TableViewPartialUpdates/PartialUpdatesViewController.swift +++ b/RxExample/RxExample/Examples/TableViewPartialUpdates/PartialUpdatesViewController.swift @@ -85,11 +85,11 @@ class PartialUpdatesViewController : ViewController { skinTableViewDataSource(reloadDataSource) self.sections.asObservable() - .bindTo(partialUpdatesTableViewOutlet.rx_itemsWithDataSource(tvAnimatedDataSource)) + .bindTo(partialUpdatesTableViewOutlet.rx_items(dataSource: tvAnimatedDataSource)) .addDisposableTo(disposeBag) self.sections.asObservable() - .bindTo(reloadTableViewOutlet.rx_itemsWithDataSource(reloadDataSource)) + .bindTo(reloadTableViewOutlet.rx_items(dataSource: reloadDataSource)) .addDisposableTo(disposeBag) // Collection view logic works, but when clicking fast because of internal bugs diff --git a/RxExample/RxExample/Examples/TableViewWithEditingCommands/TableViewWithEditingCommandsViewController.swift b/RxExample/RxExample/Examples/TableViewWithEditingCommands/TableViewWithEditingCommandsViewController.swift index 02dce321..182d5f1f 100644 --- a/RxExample/RxExample/Examples/TableViewWithEditingCommands/TableViewWithEditingCommandsViewController.swift +++ b/RxExample/RxExample/Examples/TableViewWithEditingCommands/TableViewWithEditingCommandsViewController.swift @@ -107,7 +107,7 @@ class TableViewWithEditingCommandsViewController: ViewController, UITableViewDel SectionModel(model: "Normal Users", items: $0.users) ] } - .bindTo(tableView.rx_itemsWithDataSource(dataSource)) + .bindTo(tableView.rx_items(dataSource: dataSource)) .addDisposableTo(disposeBag) tableView.rx_itemSelected diff --git a/RxExample/RxExample/Examples/WikipediaImageSearch/Views/WikipediaSearchViewController.swift b/RxExample/RxExample/Examples/WikipediaImageSearch/Views/WikipediaSearchViewController.swift index 2f0a872b..2d8858cd 100644 --- a/RxExample/RxExample/Examples/WikipediaImageSearch/Views/WikipediaSearchViewController.swift +++ b/RxExample/RxExample/Examples/WikipediaImageSearch/Views/WikipediaSearchViewController.swift @@ -78,7 +78,7 @@ class WikipediaSearchViewController: ViewController { .map { results in results.map(SearchResultViewModel.init) } - .drive(resultsTableView.rx_itemsWithCellIdentifier("WikipediaSearchCell", cellType: WikipediaSearchCell.self)) { (_, viewModel, cell) in + .drive(resultsTableView.rx_items(cellIdentifier: "WikipediaSearchCell", cellType: WikipediaSearchCell.self)) { (_, viewModel, cell) in cell.viewModel = viewModel } .addDisposableTo(disposeBag) diff --git a/Tests/RxCocoaTests/UICollectionView+RxTests.swift b/Tests/RxCocoaTests/UICollectionView+RxTests.swift index 11d8bd24..473fce59 100644 --- a/Tests/RxCocoaTests/UICollectionView+RxTests.swift +++ b/Tests/RxCocoaTests/UICollectionView+RxTests.swift @@ -66,7 +66,7 @@ class UICollectionViewTests : RxTest { let layout = UICollectionViewFlowLayout() let createView: () -> (UICollectionView, Disposable) = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) - let s = items.bindTo(collectionView.rx_itemsWithCellFactory) { (cv, index: Int, item: Int) -> UICollectionViewCell in + let s = items.bindTo(collectionView.rx_items) { (cv, index: Int, item: Int) -> UICollectionViewCell in return UICollectionViewCell(frame: CGRect(x: 1, y: 1, width: 1, height: 1)) } @@ -83,7 +83,7 @@ class UICollectionViewTests : RxTest { let createView: () -> (UICollectionView, Disposable) = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) collectionView.register(NSClassFromString("UICollectionViewCell"), forCellWithReuseIdentifier: "a") - let s = items.bindTo(collectionView.rx_itemsWithCellIdentifier("a")) { (index: Int, item: Int, cell) in + let s = items.bindTo(collectionView.rx_items(cellIdentifier: "a")) { (index: Int, item: Int, cell) in } @@ -100,7 +100,7 @@ class UICollectionViewTests : RxTest { let createView: () -> (UICollectionView, Disposable) = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) collectionView.register(NSClassFromString("UICollectionViewCell"), forCellWithReuseIdentifier: "a") - let s = items.bindTo(collectionView.rx_itemsWithCellIdentifier("a", cellType: UICollectionViewCell.self)) { (index: Int, item: Int, cell) in + let s = items.bindTo(collectionView.rx_items(cellIdentifier: "a", cellType: UICollectionViewCell.self)) { (index: Int, item: Int, cell) in } @@ -116,7 +116,7 @@ class UICollectionViewTests : RxTest { let createView: () -> (UICollectionView, Disposable) = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) - let s = items.bindTo(collectionView.rx_itemsWithCellFactory) { (cv, index: Int, item: Int) -> UICollectionViewCell in + let s = items.bindTo(collectionView.rx_items) { (cv, index: Int, item: Int) -> UICollectionViewCell in return UICollectionViewCell(frame: CGRect(x: 1, y: 1, width: 1, height: 1)) } @@ -147,7 +147,7 @@ class UICollectionViewTests : RxTest { let createView: () -> (UICollectionView, Disposable) = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) collectionView.register(NSClassFromString("UICollectionViewCell"), forCellWithReuseIdentifier: "a") - let dataSourceSubscription = items.bindTo(collectionView.rx_itemsWithCellIdentifier("a")) { (index: Int, item: Int, cell) in + let dataSourceSubscription = items.bindTo(collectionView.rx_items(cellIdentifier: "a")) { (index: Int, item: Int, cell) in } @@ -178,7 +178,7 @@ class UICollectionViewTests : RxTest { let createView: () -> (UICollectionView, Disposable) = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) - let s = items.bindTo(collectionView.rx_itemsWithCellFactory) { (cv, index: Int, item: Int) -> UICollectionViewCell in + let s = items.bindTo(collectionView.rx_items) { (cv, index: Int, item: Int) -> UICollectionViewCell in return UICollectionViewCell(frame: CGRect(x: 1, y: 1, width: 1, height: 1)) } @@ -209,7 +209,7 @@ class UICollectionViewTests : RxTest { let createView: () -> (UICollectionView, Disposable) = { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) collectionView.register(NSClassFromString("UICollectionViewCell"), forCellWithReuseIdentifier: "a") - let dataSourceSubscription = items.bindTo(collectionView.rx_itemsWithCellIdentifier("a")) { (index: Int, item: Int, cell) in + let dataSourceSubscription = items.bindTo(collectionView.rx_items(cellIdentifier: "a")) { (index: Int, item: Int, cell) in } @@ -241,7 +241,7 @@ class UICollectionViewTests : RxTest { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) collectionView.register(NSClassFromString("UICollectionViewCell"), forCellWithReuseIdentifier: "a") let dataSource = SectionedViewDataSourceMock() - let dataSourceSubscription = items.bindTo(collectionView.rx_itemsWithDataSource(dataSource)) + let dataSourceSubscription = items.bindTo(collectionView.rx_items(dataSource: dataSource)) return (collectionView, dataSourceSubscription) @@ -268,7 +268,7 @@ extension UICollectionViewTests { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "a") let dataSource = SectionedViewDataSourceMock() - dataSourceSubscription = items.bindTo(collectionView.rx_itemsWithDataSource(dataSource)) + dataSourceSubscription = items.bindTo(collectionView.rx_items(dataSource: dataSource)) _ = dataSource.rx_deallocated.subscribeNext { _ in dataSourceDeallocated = true @@ -291,7 +291,7 @@ extension UICollectionViewTests { let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), collectionViewLayout: layout) collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "a") let dataSource = SectionedViewDataSourceMock() - _ = items.bindTo(collectionView.rx_itemsWithDataSource(dataSource)) + _ = items.bindTo(collectionView.rx_items(dataSource: dataSource)) _ = dataSource.rx_deallocated.subscribeNext { _ in dataSourceDeallocated = true diff --git a/Tests/RxCocoaTests/UITableView+RxTests.swift b/Tests/RxCocoaTests/UITableView+RxTests.swift index d8a7bf36..dff25d44 100644 --- a/Tests/RxCocoaTests/UITableView+RxTests.swift +++ b/Tests/RxCocoaTests/UITableView+RxTests.swift @@ -181,7 +181,7 @@ class UITableViewTests : RxTest { let createView: () -> (UITableView, Disposable) = { let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) - let dataSourceSubscription = items.bindTo(tableView.rx_itemsWithCellFactory) { (tv, index: Int, item: Int) -> UITableViewCell in + let dataSourceSubscription = items.bindTo(tableView.rx_items) { (tv, index: Int, item: Int) -> UITableViewCell in return UITableViewCell(style: .default, reuseIdentifier: "Identity") } @@ -196,7 +196,7 @@ class UITableViewTests : RxTest { let createView: () -> (UITableView, Disposable) = { let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) tableView.register(NSClassFromString("UITableViewCell"), forCellReuseIdentifier: "a") - let dataSourceSubscription = items.bindTo(tableView.rx_itemsWithCellIdentifier("a")) { (index: Int, item: Int, cell) in + let dataSourceSubscription = items.bindTo(tableView.rx_items(cellIdentifier: "a")) { (index: Int, item: Int, cell) in } @@ -211,7 +211,7 @@ class UITableViewTests : RxTest { let createView: () -> (UITableView, Disposable) = { let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) tableView.register(NSClassFromString("UITableViewCell"), forCellReuseIdentifier: "a") - let dataSourceSubscription = items.bindTo(tableView.rx_itemsWithCellIdentifier("a", cellType: UITableViewCell.self)) { (index: Int, item: Int, cell) in + let dataSourceSubscription = items.bindTo(tableView.rx_items(cellIdentifier: "a", cellType: UITableViewCell.self)) { (index: Int, item: Int, cell) in } @@ -225,7 +225,7 @@ class UITableViewTests : RxTest { let createView: () -> (UITableView, Disposable) = { let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) - let dataSourceSubscription = items.bindTo(tableView.rx_itemsWithCellFactory) { (tv, index: Int, item: Int) -> UITableViewCell in + let dataSourceSubscription = items.bindTo(tableView.rx_items) { (tv, index: Int, item: Int) -> UITableViewCell in return UITableViewCell(style: .default, reuseIdentifier: "Identity") } @@ -255,7 +255,7 @@ class UITableViewTests : RxTest { let createView: () -> (UITableView, Disposable) = { let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) tableView.register(NSClassFromString("UITableViewCell"), forCellReuseIdentifier: "a") - let dataSourceSubscription = items.bindTo(tableView.rx_itemsWithCellIdentifier("a")) { (index: Int, item: Int, cell) in + let dataSourceSubscription = items.bindTo(tableView.rx_items(cellIdentifier: "a")) { (index: Int, item: Int, cell) in } @@ -284,7 +284,7 @@ class UITableViewTests : RxTest { let createView: () -> (UITableView, Disposable) = { let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) - let dataSourceSubscription = items.bindTo(tableView.rx_itemsWithCellFactory) { (tv, index: Int, item: Int) -> UITableViewCell in + let dataSourceSubscription = items.bindTo(tableView.rx_items) { (tv, index: Int, item: Int) -> UITableViewCell in return UITableViewCell(style: .default, reuseIdentifier: "Identity") } @@ -314,7 +314,7 @@ class UITableViewTests : RxTest { let createView: () -> (UITableView, Disposable) = { let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) tableView.register(NSClassFromString("UITableViewCell"), forCellReuseIdentifier: "a") - let dataSourceSubscription = items.bindTo(tableView.rx_itemsWithCellIdentifier("a")) { (index: Int, item: Int, cell) in + let dataSourceSubscription = items.bindTo(tableView.rx_items(cellIdentifier: "a")) { (index: Int, item: Int, cell) in } @@ -345,7 +345,7 @@ class UITableViewTests : RxTest { let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) tableView.register(NSClassFromString("UITableViewCell"), forCellReuseIdentifier: "a") let dataSource = SectionedViewDataSourceMock() - let dataSourceSubscription = items.bindTo(tableView.rx_itemsWithDataSource(dataSource)) + let dataSourceSubscription = items.bindTo(tableView.rx_items(dataSource: dataSource)) return (tableView, dataSourceSubscription) } @@ -370,7 +370,7 @@ extension UITableViewTests { let items: Observable<[Int]> = Observable.just([1, 2, 3]) let dataSource = SectionedViewDataSourceMock() let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) - dataSourceSubscription = items.bindTo(tableView.rx_itemsWithDataSource(dataSource)) + dataSourceSubscription = items.bindTo(tableView.rx_items(dataSource: dataSource)) _ = dataSource.rx_deallocated.subscribeNext { _ in dataSourceDeallocated = true @@ -392,7 +392,7 @@ extension UITableViewTests { let items: Observable<[Int]> = Observable.just([1, 2, 3]) let dataSource = SectionedViewDataSourceMock() - _ = items.bindTo(tableView.rx_itemsWithDataSource(dataSource)) + _ = items.bindTo(tableView.rx_items(dataSource: dataSource)) _ = dataSource.rx_deallocated.subscribeNext { _ in dataSourceDeallocated = true From d1cde77b18326b6ae27055b610b6f52737df7381 Mon Sep 17 00:00:00 2001 From: Krunoslav Zaher Date: Sun, 7 Aug 2016 18:08:13 +0200 Subject: [PATCH 23/52] Modernizes image view extensions. --- RxCocoa/OSX/NSImageView+Rx.swift | 25 ++++++++++++++++- RxCocoa/iOS/UIImageView+Rx.swift | 27 +++++++++++++++++-- .../PartialUpdatesViewController.swift | 2 +- .../Views/WikipediaSearchCell.swift | 2 +- 4 files changed, 51 insertions(+), 5 deletions(-) diff --git a/RxCocoa/OSX/NSImageView+Rx.swift b/RxCocoa/OSX/NSImageView+Rx.swift index 828af52c..a28b2c1e 100644 --- a/RxCocoa/OSX/NSImageView+Rx.swift +++ b/RxCocoa/OSX/NSImageView+Rx.swift @@ -26,6 +26,7 @@ extension NSImageView { - parameter transitionType: Optional transition type while setting the image (kCATransitionFade, kCATransitionMoveIn, ...) */ + @available(*, deprecated, renamed: "rx_image(transitionType:)") public func rx_imageAnimated(_ transitionType: String?) -> AnyObserver { return UIBindingObserver(UIElement: self) { control, value in if let transitionType = transitionType { @@ -43,5 +44,27 @@ extension NSImageView { control.image = value }.asObserver() } - + + /** + Bindable sink for `image` property. + + - parameter transitionType: Optional transition type while setting the image (kCATransitionFade, kCATransitionMoveIn, ...) + */ + public func rx_image(transitionType: String? = nil) -> AnyObserver { + return UIBindingObserver(UIElement: self) { control, value in + if let transitionType = transitionType { + if value != nil { + let transition = CATransition() + transition.duration = 0.25 + transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) + transition.type = transitionType + control.layer?.add(transition, forKey: kCATransition) + } + } + else { + control.layer?.removeAllAnimations() + } + control.image = value + }.asObserver() + } } diff --git a/RxCocoa/iOS/UIImageView+Rx.swift b/RxCocoa/iOS/UIImageView+Rx.swift index 1f99be20..8b68578b 100644 --- a/RxCocoa/iOS/UIImageView+Rx.swift +++ b/RxCocoa/iOS/UIImageView+Rx.swift @@ -20,7 +20,7 @@ extension UIImageView { Bindable sink for `image` property. */ public var rx_image: AnyObserver { - return self.rx_imageAnimated(nil) + return self.rx_image(transitionType: nil) } /** @@ -28,6 +28,7 @@ extension UIImageView { - parameter transitionType: Optional transition type while setting the image (kCATransitionFade, kCATransitionMoveIn, ...) */ + @available(*, deprecated, renamed: "rx_image(transitionType:)") public func rx_imageAnimated(_ transitionType: String?) -> AnyObserver { return UIBindingObserver(UIElement: self) { imageView, image in if let transitionType = transitionType { @@ -45,7 +46,29 @@ extension UIImageView { imageView.image = image }.asObserver() } - + + /** + Bindable sink for `image` property. + + - parameter transitionType: Optional transition type while setting the image (kCATransitionFade, kCATransitionMoveIn, ...) + */ + public func rx_image(transitionType: String? = nil) -> AnyObserver { + return UIBindingObserver(UIElement: self) { imageView, image in + if let transitionType = transitionType { + if image != nil { + let transition = CATransition() + transition.duration = 0.25 + transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) + transition.type = transitionType + imageView.layer.add(transition, forKey: kCATransition) + } + } + else { + imageView.layer.removeAllAnimations() + } + imageView.image = image + }.asObserver() + } } #endif diff --git a/RxExample/RxExample/Examples/TableViewPartialUpdates/PartialUpdatesViewController.swift b/RxExample/RxExample/Examples/TableViewPartialUpdates/PartialUpdatesViewController.swift index 03449af5..b7d942fe 100644 --- a/RxExample/RxExample/Examples/TableViewPartialUpdates/PartialUpdatesViewController.swift +++ b/RxExample/RxExample/Examples/TableViewPartialUpdates/PartialUpdatesViewController.swift @@ -115,7 +115,7 @@ class PartialUpdatesViewController : ViewController { let cvReloadDataSource = RxCollectionViewSectionedReloadDataSource() skinCollectionViewDataSource(cvReloadDataSource) self.sections.asObservable() - .bindTo(partialUpdatesCollectionViewOutlet.rx_itemsWithDataSource(cvReloadDataSource)) + .bindTo(partialUpdatesCollectionViewOutlet.rx_items(dataSource: cvReloadDataSource)) .addDisposableTo(disposeBag) #endif diff --git a/RxExample/RxExample/Examples/WikipediaImageSearch/Views/WikipediaSearchCell.swift b/RxExample/RxExample/Examples/WikipediaImageSearch/Views/WikipediaSearchCell.swift index 8d15eed1..6167f1a1 100644 --- a/RxExample/RxExample/Examples/WikipediaImageSearch/Views/WikipediaSearchCell.swift +++ b/RxExample/RxExample/Examples/WikipediaImageSearch/Views/WikipediaSearchCell.swift @@ -42,7 +42,7 @@ public class WikipediaSearchCell: UITableViewCell { let reachabilityService = Dependencies.sharedDependencies.reachabilityService viewModel.imageURLs - .drive(self.imagesOutlet.rx_itemsWithCellIdentifier("ImageCell", cellType: CollectionViewImageCell.self)) { [weak self] (_, url, cell) in + .drive(self.imagesOutlet.rx_items(cellIdentifier: "ImageCell", cellType: CollectionViewImageCell.self)) { [weak self] (_, url, cell) in cell.downloadableImage = self?.imageService.imageFromURL(url, reachabilityService: reachabilityService) ?? Observable.empty() } .addDisposableTo(disposeBag) From 441a4a22db987c109bb0067accffbfdc5cbe9570 Mon Sep 17 00:00:00 2001 From: Krunoslav Zaher Date: Sun, 7 Aug 2016 18:24:33 +0200 Subject: [PATCH 24/52] Modernizes doOn operator. --- .../CocoaUnits/Driver/Driver+Operators.swift | 29 +++++++++++-- RxCocoa/Common/DelegateProxyType.swift | 4 +- RxCocoa/iOS/UICollectionView+Rx.swift | 4 +- RxCocoa/iOS/UITableView+Rx.swift | 4 +- RxSwift/Observables/Observable+Single.swift | 42 ++++++++++++++++--- 5 files changed, 67 insertions(+), 16 deletions(-) diff --git a/RxCocoa/Common/CocoaUnits/Driver/Driver+Operators.swift b/RxCocoa/Common/CocoaUnits/Driver/Driver+Operators.swift index 7c7e9ddb..2438a8d8 100644 --- a/RxCocoa/Common/CocoaUnits/Driver/Driver+Operators.swift +++ b/RxCocoa/Common/CocoaUnits/Driver/Driver+Operators.swift @@ -120,6 +120,7 @@ extension DriverConvertibleType { - returns: The source sequence with the side-effecting behavior applied. */ // @warn_unused_result(message:"http://git.io/rxs.uo") + @available(*, deprecated, renamed: "do(onNext:onError:onCompleted:)") public func doOn(_ eventHandler: (Event) -> Void) -> Driver { let source = self.asObservable() @@ -137,6 +138,7 @@ extension DriverConvertibleType { - returns: The source sequence with the side-effecting behavior applied. */ // @warn_unused_result(message:"http://git.io/rxs.uo") + @available(*, deprecated, renamed: "do(onNext:onError:onCompleted:)") public func doOn(onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil) -> Driver { let source = self.asObservable() @@ -152,9 +154,10 @@ extension DriverConvertibleType { - returns: The source sequence with the side-effecting behavior applied. */ // @warn_unused_result(message:"http://git.io/rxs.uo") - public func `do`(onNext: ((E) -> Void)) + @available(*, deprecated, renamed: "do(onNext:)") + public func doOnNext(_ onNext: ((E) -> Void)) -> Driver { - return self.doOn(onNext: onNext) + return self.do(onNext: onNext) } /** @@ -164,9 +167,27 @@ extension DriverConvertibleType { - returns: The source sequence with the side-effecting behavior applied. */ // @warn_unused_result(message:"http://git.io/rxs.uo") - public func `do`(onCompleted: (() -> Void)) + @available(*, deprecated, renamed: "do(onCompleted:)") + public func doOnCompleted(_ onCompleted: (() -> Void)) -> Driver { - return self.doOn(onCompleted: onCompleted) + return self.do(onCompleted: onCompleted) + } + + /** + Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onError: Action to invoke upon errored termination of the observable sequence. This callback will never be invoked since driver can't error out. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - returns: The source sequence with the side-effecting behavior applied. + */ + // @warn_unused_result(message:"http://git.io/rxs.uo") + public func `do`(onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil) + -> Driver { + let source = self.asObservable() + .doOn(onNext: onNext, onError: onError, onCompleted: onCompleted) + + return Driver(source) } } diff --git a/RxCocoa/Common/DelegateProxyType.swift b/RxCocoa/Common/DelegateProxyType.swift index f41782a6..893ccb23 100644 --- a/RxCocoa/Common/DelegateProxyType.swift +++ b/RxCocoa/Common/DelegateProxyType.swift @@ -241,7 +241,7 @@ extension DelegateProxyType { } extension ObservableType { - func subscribeProxyDataSourceForObject(_ object: AnyObject, dataSource: AnyObject, retainDataSource: Bool, binding: (P, Event) -> Void) + func subscribeProxyDataSource(ofObject object: AnyObject, dataSource: AnyObject, retainDataSource: Bool, binding: (P, Event) -> Void) -> Disposable { let proxy = P.proxyForObject(object) let disposable = P.installForwardDelegate(dataSource, retainDelegate: retainDataSource, onProxyForObject: object) @@ -275,4 +275,4 @@ extension ObservableType { return CompositeDisposable(subscription, disposable) } -} \ No newline at end of file +} diff --git a/RxCocoa/iOS/UICollectionView+Rx.swift b/RxCocoa/iOS/UICollectionView+Rx.swift index eba9f981..fb81bcce 100644 --- a/RxCocoa/iOS/UICollectionView+Rx.swift +++ b/RxCocoa/iOS/UICollectionView+Rx.swift @@ -224,7 +224,7 @@ extension UICollectionView { -> Disposable { return { source in - return source.subscribeProxyDataSourceForObject(self, dataSource: dataSource, retainDataSource: true) { [weak self] (_: RxCollectionViewDataSourceProxy, event) -> Void in + return source.subscribeProxyDataSource(ofObject: self, dataSource: dataSource, retainDataSource: true) { [weak self] (_: RxCollectionViewDataSourceProxy, event) -> Void in guard let collectionView = self else { return } @@ -281,7 +281,7 @@ extension UICollectionView { -> Disposable { return { source in - return source.subscribeProxyDataSourceForObject(self, dataSource: dataSource, retainDataSource: true) { [weak self] (_: RxCollectionViewDataSourceProxy, event) -> Void in + return source.subscribeProxyDataSource(ofObject: self, dataSource: dataSource, retainDataSource: true) { [weak self] (_: RxCollectionViewDataSourceProxy, event) -> Void in guard let collectionView = self else { return } diff --git a/RxCocoa/iOS/UITableView+Rx.swift b/RxCocoa/iOS/UITableView+Rx.swift index 0c55d209..74b5154a 100644 --- a/RxCocoa/iOS/UITableView+Rx.swift +++ b/RxCocoa/iOS/UITableView+Rx.swift @@ -226,7 +226,7 @@ extension UITableView { -> Disposable { return { source in // There needs to be a strong retaining here because - return source.subscribeProxyDataSourceForObject(self, dataSource: dataSource, retainDataSource: true) { [weak self] (_: RxTableViewDataSourceProxy, event) -> Void in + return source.subscribeProxyDataSource(ofObject: self, dataSource: dataSource, retainDataSource: true) { [weak self] (_: RxTableViewDataSourceProxy, event) -> Void in guard let tableView = self else { return } @@ -288,7 +288,7 @@ extension UITableView { -> Disposable { return { source in // There needs to be a strong retaining here because - return source.subscribeProxyDataSourceForObject(self, dataSource: dataSource, retainDataSource: true) { [weak self] (_: RxTableViewDataSourceProxy, event) -> Void in + return source.subscribeProxyDataSource(ofObject: self, dataSource: dataSource, retainDataSource: true) { [weak self] (_: RxTableViewDataSourceProxy, event) -> Void in guard let tableView = self else { return } diff --git a/RxSwift/Observables/Observable+Single.swift b/RxSwift/Observables/Observable+Single.swift index faee948b..aa8db913 100644 --- a/RxSwift/Observables/Observable+Single.swift +++ b/RxSwift/Observables/Observable+Single.swift @@ -84,6 +84,7 @@ extension ObservableType { - returns: The source sequence with the side-effecting behavior applied. */ // @warn_unused_result(message:"http://git.io/rxs.uo") + @available(*, deprecated, renamed: "do(onNext:onError:onCompleted:)") public func doOn(_ eventHandler: (Event) throws -> Void) -> Observable { return Do(source: self.asObservable(), eventHandler: eventHandler) @@ -100,6 +101,7 @@ extension ObservableType { - returns: The source sequence with the side-effecting behavior applied. */ // @warn_unused_result(message:"http://git.io/rxs.uo") + @available(*, deprecated, renamed: "do(onNext:onError:onCompleted:)") public func doOn(onNext: ((E) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil) -> Observable { return Do(source: self.asObservable()) { e in @@ -121,9 +123,10 @@ extension ObservableType { - returns: The source sequence with the side-effecting behavior applied. */ // @warn_unused_result(message:"http://git.io/rxs.uo") - public func `do`(onNext: ((E) throws -> Void)) + @available(*, deprecated, renamed: "do(onNext:)") + public func doOnNext(onNext: ((E) throws -> Void)) -> Observable { - return self.doOn(onNext: onNext) + return self.do(onNext: onNext) } /** @@ -133,9 +136,10 @@ extension ObservableType { - returns: The source sequence with the side-effecting behavior applied. */ // @warn_unused_result(message:"http://git.io/rxs.uo") - public func `do`(onError: ((Swift.Error) throws -> Void)) + @available(*, deprecated, renamed: "do(onError:)") + public func doOnError(onError: ((Swift.Error) throws -> Void)) -> Observable { - return self.doOn(onError: onError) + return self.do(onError: onError) } /** @@ -145,9 +149,35 @@ extension ObservableType { - returns: The source sequence with the side-effecting behavior applied. */ // @warn_unused_result(message:"http://git.io/rxs.uo") - public func `do`(onCompleted: (() throws -> Void)) + @available(*, deprecated, renamed: "do(onCompleted:)") + public func doOnCompleted(onCompleted: (() throws -> Void)) -> Observable { - return self.doOn(onCompleted: onCompleted) + return self.do(onCompleted: onCompleted) + } + + /** + Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - returns: The source sequence with the side-effecting behavior applied. + */ + // @warn_unused_result(message:"http://git.io/rxs.uo") + public func `do`(onNext: ((E) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil) + -> Observable { + return Do(source: self.asObservable()) { e in + switch e { + case .next(let element): + try onNext?(element) + case .error(let e): + try onError?(e) + case .completed: + try onCompleted?() + } + } } } From 8a58deaa2b3eb7f0e07214c611ce2e5b082f3535 Mon Sep 17 00:00:00 2001 From: Krunoslav Zaher Date: Sun, 7 Aug 2016 18:54:23 +0200 Subject: [PATCH 25/52] Deprecates `toObservable` in favor of `from` operator. --- RxCocoa/Common/CocoaUnits/Driver/Driver.swift | 2 +- .../Implementations/Sequence.swift | 31 ++++------ RxSwift/Observables/Observable+Creation.swift | 32 ++++++++++- .../Tests/Observable+CreationTest.swift | 56 +++++++++---------- .../Tests/Observable+MultipleTest.swift | 12 +--- .../Tests/Observable+TimeTest.swift | 2 +- 6 files changed, 71 insertions(+), 64 deletions(-) diff --git a/RxCocoa/Common/CocoaUnits/Driver/Driver.swift b/RxCocoa/Common/CocoaUnits/Driver/Driver.swift index 0844fe1d..67a82d97 100644 --- a/RxCocoa/Common/CocoaUnits/Driver/Driver.swift +++ b/RxCocoa/Common/CocoaUnits/Driver/Driver.swift @@ -145,7 +145,7 @@ extension Driver { */ // @warn_unused_result(message:"http://git.io/rxs.uo") public static func of(_ elements: E ...) -> Driver { - let source = elements.toObservable(driverSubscribeOnScheduler) + let source = Observable.from(elements, scheduler: driverSubscribeOnScheduler) return Driver(raw: source) } } diff --git a/RxSwift/Observables/Implementations/Sequence.swift b/RxSwift/Observables/Implementations/Sequence.swift index fa8c5d40..453c32a2 100644 --- a/RxSwift/Observables/Implementations/Sequence.swift +++ b/RxSwift/Observables/Implementations/Sequence.swift @@ -8,8 +8,8 @@ import Foundation -class ObservableSequenceSink : Sink { - typealias Parent = ObservableSequence +class ObservableSequenceSink : Sink { + typealias Parent = ObservableSequence private let _parent: Parent @@ -19,10 +19,11 @@ class ObservableSequenceSink : Sink { } func run() -> Disposable { - return _parent._scheduler!.scheduleRecursive((0, _parent._elements)) { (state, recurse) in - if state.0 < state.1.count { - self.forwardOn(.next(state.1[state.0])) - recurse((state.0 + 1, state.1)) + return _parent._scheduler.scheduleRecursive((_parent._elements.makeIterator(), _parent._elements)) { (iterator, recurse) in + var mutableIterator = iterator + if let next = mutableIterator.0.next() { + self.forwardOn(.next(next)) + recurse(mutableIterator) } else { self.forwardOn(.completed) @@ -31,26 +32,16 @@ class ObservableSequenceSink : Sink { } } -class ObservableSequence : Producer { - private let _elements: [E] - private let _scheduler: ImmediateSchedulerType? +class ObservableSequence : Producer { + private let _elements: S + private let _scheduler: ImmediateSchedulerType - init(elements: [E], scheduler: ImmediateSchedulerType?) { + init(elements: S, scheduler: ImmediateSchedulerType) { _elements = elements _scheduler = scheduler } override func subscribe(_ observer: O) -> Disposable { - // optimized version without scheduler - guard _scheduler != nil else { - for element in _elements { - observer.on(.next(element)) - } - - observer.on(.completed) - return NopDisposable.instance - } - let sink = ObservableSequenceSink(parent: self, observer: observer) sink.disposable = sink.run() return sink diff --git a/RxSwift/Observables/Observable+Creation.swift b/RxSwift/Observables/Observable+Creation.swift index 1335e570..9f30dfc9 100644 --- a/RxSwift/Observables/Observable+Creation.swift +++ b/RxSwift/Observables/Observable+Creation.swift @@ -99,7 +99,7 @@ extension Observable { - returns: The observable sequence whose elements are pulled from the given arguments. */ // @warn_unused_result(message:"http://git.io/rxs.uo") - public static func of(_ elements: E ..., scheduler: ImmediateSchedulerType? = nil) -> Observable { + public static func of(_ elements: E ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { return ObservableSequence(elements: elements, scheduler: scheduler) } @@ -191,7 +191,8 @@ extension Sequence { - returns: The observable sequence whose elements are pulled from the given enumerable sequence. */ // @warn_unused_result(message:"http://git.io/rxs.uo") - public func toObservable(_ scheduler: ImmediateSchedulerType? = nil) -> Observable { + @available(*, deprecated, renamed: "Observable.from()") + public func toObservable(_ scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { return ObservableSequence(elements: Array(self), scheduler: scheduler) } } @@ -205,7 +206,32 @@ extension Array { - returns: The observable sequence whose elements are pulled from the given enumerable sequence. */ // @warn_unused_result(message:"http://git.io/rxs.uo") - public func toObservable(_ scheduler: ImmediateSchedulerType? = nil) -> Observable { + @available(*, deprecated, renamed: "Observable.from()") + public func toObservable(_ scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { return ObservableSequence(elements: self, scheduler: scheduler) } } + +extension Observable { + /** + Converts an array to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ array: [E], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + return ObservableSequence(elements: array, scheduler: scheduler) + } + + /** + Converts a sequence to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ sequence: S, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + return ObservableSequence(elements: sequence, scheduler: scheduler) + } +} diff --git a/Tests/RxSwiftTests/Tests/Observable+CreationTest.swift b/Tests/RxSwiftTests/Tests/Observable+CreationTest.swift index 808943b2..bd675c84 100644 --- a/Tests/RxSwiftTests/Tests/Observable+CreationTest.swift +++ b/Tests/RxSwiftTests/Tests/Observable+CreationTest.swift @@ -92,27 +92,12 @@ extension ObservableCreationTests { } } -// MARK: toObservable +// MARK: from extension ObservableCreationTests { - func testToObservable_complete_immediate() { + func testFromArray_complete_immediate() { let scheduler = TestScheduler(initialClock: 0) let res = scheduler.start { - [3, 1, 2, 4].toObservable() - } - - XCTAssertEqual(res.events, [ - next(200, 3), - next(200, 1), - next(200, 2), - next(200, 4), - completed(200) - ]) - } - - func testToObservable_complete() { - let scheduler = TestScheduler(initialClock: 0) - let res = scheduler.start { - [3, 1, 2, 4].toObservable(scheduler) + Observable.from([3, 1, 2, 4], scheduler: scheduler) } XCTAssertEqual(res.events, [ @@ -124,10 +109,25 @@ extension ObservableCreationTests { ]) } - func testToObservable_dispose() { + func testFromArray_complete() { + let scheduler = TestScheduler(initialClock: 0) + let res = scheduler.start { + Observable.from([3, 1, 2, 4], scheduler: scheduler) + } + + XCTAssertEqual(res.events, [ + next(201, 3), + next(202, 1), + next(203, 2), + next(204, 4), + completed(205) + ]) + } + + func testFromArray_dispose() { let scheduler = TestScheduler(initialClock: 0) let res = scheduler.start(203) { - [3, 1, 2, 4].toObservable(scheduler) + Observable.from([3, 1, 2, 4], scheduler: scheduler) } XCTAssertEqual(res.events, [ @@ -184,25 +184,25 @@ extension ObservableCreationTests { // MARK: toObservable extension ObservableCreationTests { - func testToObservableAnySequence_basic_immediate() { + func testFromAnySequence_basic_immediate() { let scheduler = TestScheduler(initialClock: 0) let res = scheduler.start { - AnySequence([3, 1, 2, 4]).toObservable() + Observable.from(AnySequence([3, 1, 2, 4]), scheduler: scheduler) } XCTAssertEqual(res.events, [ - next(200, 3), - next(200, 1), - next(200, 2), - next(200, 4), - completed(200) + next(201, 3), + next(202, 1), + next(203, 2), + next(204, 4), + completed(205) ]) } func testToObservableAnySequence_basic_testScheduler() { let scheduler = TestScheduler(initialClock: 0) let res = scheduler.start { - AnySequence([3, 1, 2, 4]).toObservable(scheduler) + Observable.from(AnySequence([3, 1, 2, 4]), scheduler: scheduler) } XCTAssertEqual(res.events, [ diff --git a/Tests/RxSwiftTests/Tests/Observable+MultipleTest.swift b/Tests/RxSwiftTests/Tests/Observable+MultipleTest.swift index b669a745..f3b81cdf 100644 --- a/Tests/RxSwiftTests/Tests/Observable+MultipleTest.swift +++ b/Tests/RxSwiftTests/Tests/Observable+MultipleTest.swift @@ -2500,17 +2500,7 @@ extension ObservableMultipleTest { // MARK: combine latest extension ObservableMultipleTest { - func testCombineLatest_DeadlockSimple() { - var nEvents = 0 - - let observable = Observable.combineLatest(Observable.of(0, 1, 2), Observable.of(0, 1, 2)) { $0 + $1 } - _ = observable.subscribeNext { n in - nEvents += 1 - } - - XCTAssertEqual(nEvents, 3) - } - + func testCombineLatest_DeadlockErrorAfterN() { var nEvents = 0 diff --git a/Tests/RxSwiftTests/Tests/Observable+TimeTest.swift b/Tests/RxSwiftTests/Tests/Observable+TimeTest.swift index b11de735..1a68a0df 100644 --- a/Tests/RxSwiftTests/Tests/Observable+TimeTest.swift +++ b/Tests/RxSwiftTests/Tests/Observable+TimeTest.swift @@ -261,7 +261,7 @@ extension ObservableTimeTest { let start = Date() - let a = try! [Observable.just(0), Observable.never()].toObservable().concat() + let a = try! Observable.from([Observable.just(0), Observable.never()]).concat() .throttle(2.0, scheduler: scheduler) .toBlocking() .first() From 3637153169823daff65e670f7aa965092b5207dc Mon Sep 17 00:00:00 2001 From: Krunoslav Zaher Date: Sun, 7 Aug 2016 18:59:36 +0200 Subject: [PATCH 26/52] Fixes warnings. --- .../Calculator/CalculatorViewController.swift | 3 +-- RxExample/RxExample/OSX/Main.storyboard | 26 +++++++++---------- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/RxExample/RxExample/Examples/Calculator/CalculatorViewController.swift b/RxExample/RxExample/Examples/Calculator/CalculatorViewController.swift index 26a65a89..176e8b1d 100644 --- a/RxExample/RxExample/Examples/Calculator/CalculatorViewController.swift +++ b/RxExample/RxExample/Examples/Calculator/CalculatorViewController.swift @@ -69,8 +69,7 @@ class CalculatorViewController: ViewController { nineButton.rx_tap.map { _ in .addNumber("9") } ] - commands - .toObservable() + Observable.from(commands) .merge() .scan(CalculatorState.CLEAR_STATE) { a, x in return a.tranformState(x) diff --git a/RxExample/RxExample/OSX/Main.storyboard b/RxExample/RxExample/OSX/Main.storyboard index 64e20818..3b0674fc 100644 --- a/RxExample/RxExample/OSX/Main.storyboard +++ b/RxExample/RxExample/OSX/Main.storyboard @@ -1,7 +1,7 @@ - + - + @@ -88,8 +88,8 @@ - - + + @@ -99,8 +99,8 @@ -