From b137b39a6f92fb198e34a3100a991ffc1ec4f6b5 Mon Sep 17 00:00:00 2001 From: KamilNatonek Date: Fri, 13 Oct 2023 09:48:15 +0200 Subject: [PATCH 1/4] MultiPlatformBleAdapter --- .../MultiplatformBleAdapter.podspec | 27 + .../MultiPlatformBLEAdapter-Bridging-Header.h | 4 + .../project.pbxproj | 1286 ++++++++++++++++ .../MultiPlatformBLEAdapter.xcscheme | 67 + .../RxBluetoothKit/AdvertisementData.swift | 62 + .../iOS/RxBluetoothKit/Array+Utils.swift | 11 + .../iOS/RxBluetoothKit/BluetoothError.swift | 195 +++ .../iOS/RxBluetoothKit/BluetoothManager.swift | 357 +++++ .../iOS/RxBluetoothKit/BluetoothState.swift | 12 + .../iOS/RxBluetoothKit/Boxes.swift | 63 + .../iOS/RxBluetoothKit/CBCentral+Uuid.swift | 9 + .../CBCentralManagerDelegateWrapper.swift | 75 + .../CBPeripheralDelegateWrapper.swift | 163 +++ .../iOS/RxBluetoothKit/Characteristic.swift | 121 ++ .../iOS/RxBluetoothKit/Descriptor.swift | 74 + .../RxBluetoothKit/DeviceIdentifiers.swift | 51 + .../iOS/RxBluetoothKit/Logging.swift | 218 +++ .../iOS/RxBluetoothKit/ManagerType.swift | 41 + .../RxBluetoothKit/Observable+Absorb.swift | 25 + .../Observable+QueueSubscribeOn.swift | 125 ++ .../Peripheral+Convenience.swift | 213 +++ .../iOS/RxBluetoothKit/Peripheral.swift | 516 +++++++ .../iOS/RxBluetoothKit/RestoredState.swift | 59 + .../iOS/RxBluetoothKit/RxBluetoothKit.h | 12 + .../RxBluetoothKit/RxCBCentralManager.swift | 149 ++ .../RxBluetoothKit/RxCBCharacteristic.swift | 51 + .../iOS/RxBluetoothKit/RxCBDescriptor.swift | 32 + .../iOS/RxBluetoothKit/RxCBPeripheral.swift | 394 +++++ .../iOS/RxBluetoothKit/RxCBService.swift | 42 + .../RxBluetoothKit/RxCentralManagerType.swift | 23 + .../RxBluetoothKit/RxCharacteristicType.swift | 24 + .../iOS/RxBluetoothKit/RxDescriptorType.swift | 21 + .../iOS/RxBluetoothKit/RxPeripheralType.swift | 76 + .../iOS/RxBluetoothKit/RxServiceType.swift | 21 + .../iOS/RxBluetoothKit/ScanOperation.swift | 30 + .../RxBluetoothKit/ScannedPeripheral.swift | 22 + .../iOS/RxBluetoothKit/Service.swift | 75 + .../iOS/RxBluetoothKit/UUIDIdentifiable.swift | 25 + .../iOS/RxBluetoothKit/Unimplemented.swift | 13 + .../iOS/RxSwift/AnyObserver.swift | 69 + .../iOS/RxSwift/Binder.swift | 59 + .../iOS/RxSwift/Cancelable.swift | 13 + .../iOS/RxSwift/Concurrency/AsyncLock.swift | 100 ++ .../iOS/RxSwift/Concurrency/Lock.swift | 23 + .../RxSwift/Concurrency/LockOwnerType.swift | 16 + .../Concurrency/SynchronizedDisposeType.swift | 18 + .../Concurrency/SynchronizedOnType.swift | 18 + .../SynchronizedUnsubscribeType.swift | 13 + .../RxSwift/ConnectableObservableType.swift | 19 + .../iOS/RxSwift/Date+Dispatch.swift | 64 + .../iOS/RxSwift/Disposable.swift | 13 + .../Disposables/AnonymousDisposable.swift | 59 + .../Disposables/BinaryDisposable.swift | 53 + .../Disposables/BooleanDisposable.swift | 34 + .../Disposables/CompositeDisposable.swift | 147 ++ .../iOS/RxSwift/Disposables/Disposables.swift | 13 + .../iOS/RxSwift/Disposables/DisposeBag.swift | 144 ++ .../iOS/RxSwift/Disposables/DisposeBase.swift | 22 + .../RxSwift/Disposables/NopDisposable.swift | 30 + .../Disposables/RefCountDisposable.swift | 112 ++ .../Disposables/ScheduledDisposable.swift | 50 + .../Disposables/SerialDisposable.swift | 73 + .../SingleAssignmentDisposable.swift | 72 + .../Disposables/SubscriptionDisposable.swift | 21 + .../iOS/RxSwift/Errors.swift | 52 + .../iOS/RxSwift/Event.swift | 104 ++ .../iOS/RxSwift/Extensions/Bag+Rx.swift | 50 + .../iOS/RxSwift/GroupedObservable.swift | 35 + .../iOS/RxSwift/ImmediateSchedulerType.swift | 36 + .../iOS/RxSwift/Observable+Concurrency.swift | 79 + .../iOS/RxSwift/Observable.swift | 31 + .../RxSwift/ObservableConvertibleType.swift | 18 + .../RxSwift/ObservableType+Extensions.swift | 174 +++ .../iOS/RxSwift/ObservableType.swift | 45 + .../iOS/RxSwift/Observables/AddRef.swift | 44 + .../iOS/RxSwift/Observables/Amb.swift | 157 ++ .../iOS/RxSwift/Observables/AsMaybe.swift | 48 + .../iOS/RxSwift/Observables/AsSingle.swift | 51 + .../iOS/RxSwift/Observables/Buffer.swift | 138 ++ .../iOS/RxSwift/Observables/Catch.swift | 275 ++++ .../CombineLatest+Collection.swift | 165 +++ .../Observables/CombineLatest+arity.swift | 843 +++++++++++ .../Observables/CombineLatest+arity.tt | 112 ++ .../RxSwift/Observables/CombineLatest.swift | 131 ++ .../iOS/RxSwift/Observables/CompactMap.swift | 76 + .../iOS/RxSwift/Observables/Concat.swift | 131 ++ .../iOS/RxSwift/Observables/Create.swift | 78 + .../iOS/RxSwift/Observables/Debounce.swift | 119 ++ .../iOS/RxSwift/Observables/Debug.swift | 102 ++ .../iOS/RxSwift/Observables/Decode.swift | 34 + .../RxSwift/Observables/DefaultIfEmpty.swift | 66 + .../iOS/RxSwift/Observables/Deferred.swift | 75 + .../iOS/RxSwift/Observables/Delay.swift | 174 +++ .../Observables/DelaySubscription.swift | 58 + .../RxSwift/Observables/Dematerialize.swift | 51 + .../Observables/DistinctUntilChanged.swift | 137 ++ .../iOS/RxSwift/Observables/Do.swift | 112 ++ .../iOS/RxSwift/Observables/ElementAt.swift | 105 ++ .../iOS/RxSwift/Observables/Empty.swift | 27 + .../iOS/RxSwift/Observables/Enumerated.swift | 61 + .../iOS/RxSwift/Observables/Error.swift | 33 + .../iOS/RxSwift/Observables/Filter.swift | 86 ++ .../iOS/RxSwift/Observables/First.swift | 41 + .../iOS/RxSwift/Observables/Generate.swift | 87 ++ .../iOS/RxSwift/Observables/GroupBy.swift | 133 ++ .../iOS/RxSwift/Observables/Just.swift | 87 ++ .../iOS/RxSwift/Observables/Map.swift | 76 + .../iOS/RxSwift/Observables/Materialize.swift | 44 + .../iOS/RxSwift/Observables/Merge.swift | 600 ++++++++ .../iOS/RxSwift/Observables/Multicast.swift | 405 ++++++ .../iOS/RxSwift/Observables/Never.swift | 27 + .../iOS/RxSwift/Observables/ObserveOn.swift | 243 ++++ .../iOS/RxSwift/Observables/Optional.swift | 95 ++ .../iOS/RxSwift/Observables/Producer.swift | 92 ++ .../iOS/RxSwift/Observables/Range.swift | 73 + .../iOS/RxSwift/Observables/Reduce.swift | 109 ++ .../iOS/RxSwift/Observables/Repeat.swift | 57 + .../iOS/RxSwift/Observables/RetryWhen.swift | 211 +++ .../iOS/RxSwift/Observables/Sample.swift | 139 ++ .../iOS/RxSwift/Observables/Scan.swift | 100 ++ .../iOS/RxSwift/Observables/Sequence.swift | 89 ++ .../Observables/ShareReplayScope.swift | 443 ++++++ .../iOS/RxSwift/Observables/SingleAsync.swift | 104 ++ .../iOS/RxSwift/Observables/Sink.swift | 75 + .../iOS/RxSwift/Observables/Skip.swift | 158 ++ .../iOS/RxSwift/Observables/SkipUntil.swift | 152 ++ .../iOS/RxSwift/Observables/SkipWhile.swift | 87 ++ .../iOS/RxSwift/Observables/StartWith.swift | 42 + .../iOS/RxSwift/Observables/SubscribeOn.swift | 103 ++ .../iOS/RxSwift/Observables/Switch.swift | 251 ++++ .../RxSwift/Observables/SwitchIfEmpty.swift | 104 ++ .../iOS/RxSwift/Observables/Take.swift | 193 +++ .../iOS/RxSwift/Observables/TakeLast.swift | 78 + .../Observables/TakeWithPredicate.swift | 285 ++++ .../iOS/RxSwift/Observables/Throttle.swift | 160 ++ .../iOS/RxSwift/Observables/Timeout.swift | 151 ++ .../iOS/RxSwift/Observables/Timer.swift | 117 ++ .../iOS/RxSwift/Observables/ToArray.swift | 64 + .../iOS/RxSwift/Observables/Using.swift | 90 ++ .../iOS/RxSwift/Observables/Window.swift | 168 +++ .../RxSwift/Observables/WithLatestFrom.swift | 151 ++ .../RxSwift/Observables/WithUnretained.swift | 58 + .../RxSwift/Observables/Zip+Collection.swift | 168 +++ .../iOS/RxSwift/Observables/Zip+arity.swift | 934 ++++++++++++ .../iOS/RxSwift/Observables/Zip+arity.tt | 120 ++ .../iOS/RxSwift/Observables/Zip.swift | 135 ++ .../iOS/RxSwift/ObserverType.swift | 40 + .../RxSwift/Observers/AnonymousObserver.swift | 30 + .../iOS/RxSwift/Observers/ObserverBase.swift | 32 + .../RxSwift/Observers/TailRecursiveSink.swift | 151 ++ .../iOS/RxSwift/Platform/AtomicInt.swift | 72 + .../RxSwift/Platform/DataStructures/Bag.swift | 181 +++ .../DataStructures/InfiniteSequence.swift | 23 + .../DataStructures/PriorityQueue.swift | 111 ++ .../Platform/DataStructures/Queue.swift | 148 ++ .../Platform/DispatchQueue+Extensions.swift | 21 + .../RxSwift/Platform/Platform.Darwin.swift | 35 + .../iOS/RxSwift/Platform/Platform.Linux.swift | 32 + .../iOS/RxSwift/Platform/RecursiveLock.swift | 34 + .../iOS/RxSwift/Reactive.swift | 80 + .../iOS/RxSwift/Rx.swift | 142 ++ .../iOS/RxSwift/RxMutableBox.swift | 53 + .../iOS/RxSwift/SchedulerType.swift | 71 + .../ConcurrentDispatchQueueScheduler.swift | 82 ++ .../Schedulers/ConcurrentMainScheduler.swift | 87 ++ .../Schedulers/CurrentThreadScheduler.swift | 131 ++ .../Schedulers/HistoricalScheduler.swift | 22 + .../HistoricalSchedulerTimeConverter.swift | 67 + .../Internal/DispatchQueueConfiguration.swift | 97 ++ .../Internal/InvocableScheduledItem.swift | 22 + .../Schedulers/Internal/InvocableType.swift | 17 + .../Schedulers/Internal/ScheduledItem.swift | 35 + .../Internal/ScheduledItemType.swift | 13 + .../RxSwift/Schedulers/MainScheduler.swift | 80 + .../Schedulers/OperationQueueScheduler.swift | 54 + .../Schedulers/RecursiveScheduler.swift | 220 +++ .../SchedulerServices+Emulation.swift | 61 + .../SerialDispatchQueueScheduler.swift | 131 ++ .../Schedulers/VirtualTimeConverterType.swift | 97 ++ .../Schedulers/VirtualTimeScheduler.swift | 267 ++++ .../iOS/RxSwift/Subjects/AsyncSubject.swift | 154 ++ .../RxSwift/Subjects/BehaviorSubject.swift | 157 ++ .../iOS/RxSwift/Subjects/PublishSubject.swift | 140 ++ .../iOS/RxSwift/Subjects/ReplaySubject.swift | 271 ++++ .../iOS/RxSwift/Subjects/SubjectType.swift | 21 + .../RxSwift/SwiftSupport/SwiftSupport.swift | 18 + .../Infallible+CombineLatest+Collection.swift | 36 + .../Infallible+CombineLatest+arity.swift | 276 ++++ .../Infallible+CombineLatest+arity.tt | 30 + .../Infallible/Infallible+Concurrency.swift | 37 + .../Traits/Infallible/Infallible+Create.swift | 55 + .../Traits/Infallible/Infallible+Debug.swift | 26 + .../Infallible/Infallible+Operators.swift | 711 +++++++++ .../Infallible/Infallible+Zip+arity.swift | 138 ++ .../Traits/Infallible/Infallible+Zip+arity.tt | 29 + .../Traits/Infallible/Infallible.swift | 102 ++ ...ObservableConvertibleType+Infallible.swift | 35 + .../Completable+AndThen.swift | 132 ++ .../PrimitiveSequence/Completable.swift | 320 ++++ .../Traits/PrimitiveSequence/Maybe.swift | 387 +++++ .../ObservableType+PrimitiveSequence.swift | 55 + .../PrimitiveSequence+Concurrency.swift | 164 +++ .../PrimitiveSequence+Zip+arity.swift | 521 +++++++ .../PrimitiveSequence+Zip+arity.tt | 82 ++ .../PrimitiveSequence/PrimitiveSequence.swift | 342 +++++ .../Traits/PrimitiveSequence/Single.swift | 403 +++++ .../iOS/classes/BleAdapter.swift | 228 +++ .../iOS/classes/BleAdapterFactory.swift | 24 + .../iOS/classes/BleClientManager.h | 17 + .../iOS/classes/BleError.swift | 309 ++++ .../iOS/classes/BleEvent.swift | 43 + .../iOS/classes/BleExtensions.swift | 214 +++ .../iOS/classes/BleModule.swift | 1290 +++++++++++++++++ .../iOS/classes/BleUtils.swift | 110 ++ .../iOS/classes/MultiPlatformBLEAdapter.h | 13 + .../iOS/classes/MultiPlatformBLEAdapter.m | 13 + .../iOS/classes/Utils/DisposableMap.swift | 32 + .../iOS/classes/Utils/SafePromise.swift | 37 + 218 files changed, 26962 insertions(+) create mode 100644 ios/MultiPlatformBleAdapter/MultiplatformBleAdapter.podspec create mode 100644 ios/MultiPlatformBleAdapter/iOS/MultiPlatformBLEAdapter-Bridging-Header.h create mode 100644 ios/MultiPlatformBleAdapter/iOS/MultiPlatformBLEAdapter.xcodeproj/project.pbxproj create mode 100644 ios/MultiPlatformBleAdapter/iOS/MultiPlatformBLEAdapter.xcodeproj/xcshareddata/xcschemes/MultiPlatformBLEAdapter.xcscheme create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/AdvertisementData.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Array+Utils.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/BluetoothError.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/BluetoothManager.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/BluetoothState.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Boxes.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/CBCentral+Uuid.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/CBCentralManagerDelegateWrapper.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/CBPeripheralDelegateWrapper.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Characteristic.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Descriptor.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/DeviceIdentifiers.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Logging.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/ManagerType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Observable+Absorb.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Observable+QueueSubscribeOn.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Peripheral+Convenience.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Peripheral.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RestoredState.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxBluetoothKit.h create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBCentralManager.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBCharacteristic.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBDescriptor.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBPeripheral.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBService.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCentralManagerType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCharacteristicType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxDescriptorType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxPeripheralType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxServiceType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/ScanOperation.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/ScannedPeripheral.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Service.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/UUIDIdentifiable.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Unimplemented.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/AnyObserver.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Binder.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Cancelable.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/AsyncLock.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/Lock.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/LockOwnerType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/SynchronizedDisposeType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/SynchronizedOnType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/ConnectableObservableType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Date+Dispatch.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposable.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/AnonymousDisposable.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/BinaryDisposable.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/BooleanDisposable.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/CompositeDisposable.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/Disposables.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/DisposeBag.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/DisposeBase.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/NopDisposable.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/RefCountDisposable.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/ScheduledDisposable.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/SerialDisposable.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/SingleAssignmentDisposable.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/SubscriptionDisposable.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Errors.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Event.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Extensions/Bag+Rx.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/GroupedObservable.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/ImmediateSchedulerType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observable+Concurrency.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observable.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/ObservableConvertibleType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/ObservableType+Extensions.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/ObservableType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/AddRef.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Amb.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/AsMaybe.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/AsSingle.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Buffer.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Catch.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CombineLatest+Collection.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CombineLatest+arity.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CombineLatest+arity.tt create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CombineLatest.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CompactMap.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Concat.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Create.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Debounce.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Debug.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Decode.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/DefaultIfEmpty.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Deferred.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Delay.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/DelaySubscription.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Dematerialize.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/DistinctUntilChanged.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Do.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/ElementAt.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Empty.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Enumerated.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Error.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Filter.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/First.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Generate.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/GroupBy.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Just.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Map.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Materialize.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Merge.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Multicast.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Never.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/ObserveOn.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Optional.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Producer.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Range.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Reduce.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Repeat.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/RetryWhen.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Sample.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Scan.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Sequence.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/ShareReplayScope.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SingleAsync.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Sink.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Skip.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SkipUntil.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SkipWhile.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/StartWith.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SubscribeOn.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Switch.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SwitchIfEmpty.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Take.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/TakeLast.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/TakeWithPredicate.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Throttle.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Timeout.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Timer.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/ToArray.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Using.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Window.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/WithLatestFrom.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/WithUnretained.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Zip+Collection.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Zip+arity.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Zip+arity.tt create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Zip.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/ObserverType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observers/AnonymousObserver.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observers/ObserverBase.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Observers/TailRecursiveSink.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/AtomicInt.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DataStructures/Bag.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DataStructures/InfiniteSequence.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DataStructures/PriorityQueue.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DataStructures/Queue.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DispatchQueue+Extensions.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/Platform.Darwin.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/Platform.Linux.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/RecursiveLock.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Reactive.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Rx.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/RxMutableBox.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/SchedulerType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/ConcurrentMainScheduler.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/CurrentThreadScheduler.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/HistoricalScheduler.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/InvocableType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/ScheduledItem.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/ScheduledItemType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/MainScheduler.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/OperationQueueScheduler.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/RecursiveScheduler.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/SchedulerServices+Emulation.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/VirtualTimeConverterType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/VirtualTimeScheduler.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Subjects/AsyncSubject.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Subjects/BehaviorSubject.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Subjects/PublishSubject.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Subjects/ReplaySubject.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Subjects/SubjectType.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/SwiftSupport/SwiftSupport.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/Infallible/Infallible+CombineLatest+Collection.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/Infallible/Infallible+CombineLatest+arity.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/Infallible/Infallible+CombineLatest+arity.tt create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/Infallible/Infallible+Concurrency.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/Infallible/Infallible+Create.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/Infallible/Infallible+Debug.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/Infallible/Infallible+Operators.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/Infallible/Infallible+Zip+arity.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/Infallible/Infallible+Zip+arity.tt create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/Infallible/Infallible.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/Infallible/ObservableConvertibleType+Infallible.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/PrimitiveSequence/Completable+AndThen.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/PrimitiveSequence/Completable.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/PrimitiveSequence/Maybe.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/PrimitiveSequence/ObservableType+PrimitiveSequence.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/PrimitiveSequence/PrimitiveSequence+Concurrency.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/PrimitiveSequence/PrimitiveSequence+Zip+arity.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/PrimitiveSequence/PrimitiveSequence+Zip+arity.tt create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/PrimitiveSequence/PrimitiveSequence.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/RxSwift/Traits/PrimitiveSequence/Single.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/classes/BleAdapter.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/classes/BleAdapterFactory.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/classes/BleClientManager.h create mode 100644 ios/MultiPlatformBleAdapter/iOS/classes/BleError.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/classes/BleEvent.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/classes/BleExtensions.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/classes/BleModule.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/classes/BleUtils.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/classes/MultiPlatformBLEAdapter.h create mode 100644 ios/MultiPlatformBleAdapter/iOS/classes/MultiPlatformBLEAdapter.m create mode 100644 ios/MultiPlatformBleAdapter/iOS/classes/Utils/DisposableMap.swift create mode 100644 ios/MultiPlatformBleAdapter/iOS/classes/Utils/SafePromise.swift diff --git a/ios/MultiPlatformBleAdapter/MultiplatformBleAdapter.podspec b/ios/MultiPlatformBleAdapter/MultiplatformBleAdapter.podspec new file mode 100644 index 000000000..8f45fd022 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/MultiplatformBleAdapter.podspec @@ -0,0 +1,27 @@ +Pod::Spec.new do |spec| + spec.name = "MultiplatformBleAdapter" + spec.version = "0.2.0" + spec.summary = "An adapter for RxBluetoothKit that exposes consist API to crossplatform libraries" + + spec.description = <<-DESC + An adapter for RxBluetoothKit that exposes consist API to crossplatform libraries + DESC + + spec.homepage = "https://github.com/Polidea/MultiPlatformBleAdapter" + spec.license = "Apache License, Version 2.0." + spec.author = { "Michał Tuszyński" => "srgtuszy@gmail.com", "Kamil Natonek" => "kamil.natonek@withintent.com" } + spec.social_media_url = "https://withintent.com" + + spec.platforms = { :ios => '11.0', :tvos => '11.0' } + + spec.swift_versions = ['4.0', '4.2', '5.0'] + spec.source = { :git => "https://github.com/dotintent/MultiPlatformBleAdapter.git", :tag => "#{spec.version}" } + + spec.source_files = "iOS/classes/**/*.{h,m,swift}", "iOS/RxBluetoothKit/**/*.{h,m,swift}", "iOS/RxSwift/**/*.{h,m,swift}" + spec.exclude_files = 'android/**/*' + + spec.frameworks = 'CoreBluetooth' + + spec.requires_arc = true + +end diff --git a/ios/MultiPlatformBleAdapter/iOS/MultiPlatformBLEAdapter-Bridging-Header.h b/ios/MultiPlatformBleAdapter/iOS/MultiPlatformBLEAdapter-Bridging-Header.h new file mode 100644 index 000000000..1b2cb5d6d --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/MultiPlatformBLEAdapter-Bridging-Header.h @@ -0,0 +1,4 @@ +// +// Use this file to import your target's public headers that you would like to expose to Swift. +// + diff --git a/ios/MultiPlatformBleAdapter/iOS/MultiPlatformBLEAdapter.xcodeproj/project.pbxproj b/ios/MultiPlatformBleAdapter/iOS/MultiPlatformBLEAdapter.xcodeproj/project.pbxproj new file mode 100644 index 000000000..4033b27c0 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/MultiPlatformBLEAdapter.xcodeproj/project.pbxproj @@ -0,0 +1,1286 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + 816FE39B234F29B3008BF70D /* BleAdapterFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = 816FE39A234F29B3008BF70D /* BleAdapterFactory.swift */; }; + 81B95B92234B256000D96D28 /* BleAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 81B95B91234B256000D96D28 /* BleAdapter.swift */; }; + 8E63F2D12AB0CE9B0010A0CB /* AtomicInt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2D02AB0CE9B0010A0CB /* AtomicInt.swift */; }; + 8E63F2D32AB0CEEC0010A0CB /* DispatchQueue+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2D22AB0CEEC0010A0CB /* DispatchQueue+Extensions.swift */; }; + 8E63F2D52AB0CF050010A0CB /* Platform.Darwin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2D42AB0CF050010A0CB /* Platform.Darwin.swift */; }; + 8E63F2D72AB0CF1E0010A0CB /* Platform.Linux.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2D62AB0CF1E0010A0CB /* Platform.Linux.swift */; }; + 8E63F2D92AB0CF400010A0CB /* RecursiveLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2D82AB0CF400010A0CB /* RecursiveLock.swift */; }; + 8E63F2DB2AB0CF730010A0CB /* Bag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2DA2AB0CF730010A0CB /* Bag.swift */; }; + 8E63F2DD2AB0CF830010A0CB /* InfiniteSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2DC2AB0CF830010A0CB /* InfiniteSequence.swift */; }; + 8E63F2DF2AB0CFB10010A0CB /* PriorityQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2DE2AB0CFB10010A0CB /* PriorityQueue.swift */; }; + 8E63F2E12AB0CFC30010A0CB /* Queue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2E02AB0CFC30010A0CB /* Queue.swift */; }; + 8E63F32B2AB0D6390010A0CB /* DefaultIfEmpty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2E32AB0D6340010A0CB /* DefaultIfEmpty.swift */; }; + 8E63F32C2AB0D6390010A0CB /* Never.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2E42AB0D6340010A0CB /* Never.swift */; }; + 8E63F32D2AB0D6390010A0CB /* GroupBy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2E62AB0D6340010A0CB /* GroupBy.swift */; }; + 8E63F32E2AB0D6390010A0CB /* Switch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2E72AB0D6340010A0CB /* Switch.swift */; }; + 8E63F32F2AB0D6390010A0CB /* WithUnretained.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2E82AB0D6340010A0CB /* WithUnretained.swift */; }; + 8E63F3302AB0D6390010A0CB /* Producer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2E92AB0D6340010A0CB /* Producer.swift */; }; + 8E63F3312AB0D6390010A0CB /* RetryWhen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2EA2AB0D6340010A0CB /* RetryWhen.swift */; }; + 8E63F3322AB0D6390010A0CB /* StartWith.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2EB2AB0D6340010A0CB /* StartWith.swift */; }; + 8E63F3332AB0D6390010A0CB /* Scan.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2EC2AB0D6340010A0CB /* Scan.swift */; }; + 8E63F3342AB0D6390010A0CB /* Using.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2ED2AB0D6350010A0CB /* Using.swift */; }; + 8E63F3352AB0D6390010A0CB /* Concat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2EE2AB0D6350010A0CB /* Concat.swift */; }; + 8E63F3362AB0D6390010A0CB /* Do.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2EF2AB0D6350010A0CB /* Do.swift */; }; + 8E63F3372AB0D6390010A0CB /* SwitchIfEmpty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2F02AB0D6350010A0CB /* SwitchIfEmpty.swift */; }; + 8E63F3382AB0D6390010A0CB /* Throttle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2F12AB0D6350010A0CB /* Throttle.swift */; }; + 8E63F3392AB0D6390010A0CB /* WithLatestFrom.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2F22AB0D6350010A0CB /* WithLatestFrom.swift */; }; + 8E63F33A2AB0D6390010A0CB /* Debounce.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2F32AB0D6350010A0CB /* Debounce.swift */; }; + 8E63F33B2AB0D6390010A0CB /* Deferred.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2F42AB0D6350010A0CB /* Deferred.swift */; }; + 8E63F33C2AB0D6390010A0CB /* Enumerated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2F52AB0D6350010A0CB /* Enumerated.swift */; }; + 8E63F33D2AB0D6390010A0CB /* Buffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2F62AB0D6350010A0CB /* Buffer.swift */; }; + 8E63F33E2AB0D6390010A0CB /* Range.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2F72AB0D6350010A0CB /* Range.swift */; }; + 8E63F33F2AB0D6390010A0CB /* Sequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2F82AB0D6350010A0CB /* Sequence.swift */; }; + 8E63F3402AB0D6390010A0CB /* SkipWhile.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2F92AB0D6350010A0CB /* SkipWhile.swift */; }; + 8E63F3412AB0D6390010A0CB /* ObserveOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2FA2AB0D6350010A0CB /* ObserveOn.swift */; }; + 8E63F3422AB0D6390010A0CB /* ElementAt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2FB2AB0D6350010A0CB /* ElementAt.swift */; }; + 8E63F3432AB0D6390010A0CB /* Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2FC2AB0D6350010A0CB /* Filter.swift */; }; + 8E63F3442AB0D6390010A0CB /* SingleAsync.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2FD2AB0D6350010A0CB /* SingleAsync.swift */; }; + 8E63F3452AB0D6390010A0CB /* Timeout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2FE2AB0D6350010A0CB /* Timeout.swift */; }; + 8E63F3462AB0D6390010A0CB /* AddRef.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F2FF2AB0D6360010A0CB /* AddRef.swift */; }; + 8E63F3472AB0D6390010A0CB /* AsSingle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3002AB0D6360010A0CB /* AsSingle.swift */; }; + 8E63F3482AB0D6390010A0CB /* CombineLatest+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3012AB0D6360010A0CB /* CombineLatest+Collection.swift */; }; + 8E63F3492AB0D6390010A0CB /* Decode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3022AB0D6360010A0CB /* Decode.swift */; }; + 8E63F34A2AB0D6390010A0CB /* Window.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3032AB0D6360010A0CB /* Window.swift */; }; + 8E63F34B2AB0D6390010A0CB /* CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3042AB0D6360010A0CB /* CompactMap.swift */; }; + 8E63F34C2AB0D6390010A0CB /* DelaySubscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3052AB0D6360010A0CB /* DelaySubscription.swift */; }; + 8E63F34D2AB0D6390010A0CB /* DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3062AB0D6360010A0CB /* DistinctUntilChanged.swift */; }; + 8E63F34E2AB0D6390010A0CB /* First.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3072AB0D6360010A0CB /* First.swift */; }; + 8E63F34F2AB0D6390010A0CB /* Amb.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3082AB0D6360010A0CB /* Amb.swift */; }; + 8E63F3502AB0D6390010A0CB /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3092AB0D6360010A0CB /* Error.swift */; }; + 8E63F3512AB0D6390010A0CB /* Generate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F30A2AB0D6360010A0CB /* Generate.swift */; }; + 8E63F3522AB0D6390010A0CB /* Materialize.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F30B2AB0D6370010A0CB /* Materialize.swift */; }; + 8E63F3532AB0D6390010A0CB /* SubscribeOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F30C2AB0D6370010A0CB /* SubscribeOn.swift */; }; + 8E63F3542AB0D6390010A0CB /* Debug.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F30D2AB0D6370010A0CB /* Debug.swift */; }; + 8E63F3552AB0D6390010A0CB /* Create.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F30E2AB0D6370010A0CB /* Create.swift */; }; + 8E63F3562AB0D6390010A0CB /* Sample.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F30F2AB0D6370010A0CB /* Sample.swift */; }; + 8E63F3572AB0D6390010A0CB /* Take.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3102AB0D6370010A0CB /* Take.swift */; }; + 8E63F3582AB0D6390010A0CB /* Merge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3112AB0D6370010A0CB /* Merge.swift */; }; + 8E63F3592AB0D6390010A0CB /* Empty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3122AB0D6370010A0CB /* Empty.swift */; }; + 8E63F35A2AB0D6390010A0CB /* Dematerialize.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3132AB0D6370010A0CB /* Dematerialize.swift */; }; + 8E63F35B2AB0D6390010A0CB /* Zip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3142AB0D6370010A0CB /* Zip.swift */; }; + 8E63F35C2AB0D6390010A0CB /* CombineLatest+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3152AB0D6370010A0CB /* CombineLatest+arity.swift */; }; + 8E63F35D2AB0D6390010A0CB /* Skip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3162AB0D6370010A0CB /* Skip.swift */; }; + 8E63F35E2AB0D6390010A0CB /* TakeLast.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3172AB0D6370010A0CB /* TakeLast.swift */; }; + 8E63F35F2AB0D6390010A0CB /* CombineLatest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3182AB0D6370010A0CB /* CombineLatest.swift */; }; + 8E63F3602AB0D6390010A0CB /* Zip+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3192AB0D6370010A0CB /* Zip+Collection.swift */; }; + 8E63F3612AB0D6390010A0CB /* ShareReplayScope.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F31A2AB0D6370010A0CB /* ShareReplayScope.swift */; }; + 8E63F3622AB0D6390010A0CB /* Sink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F31B2AB0D6380010A0CB /* Sink.swift */; }; + 8E63F3632AB0D6390010A0CB /* Delay.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F31C2AB0D6380010A0CB /* Delay.swift */; }; + 8E63F3642AB0D6390010A0CB /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F31D2AB0D6380010A0CB /* Optional.swift */; }; + 8E63F3652AB0D6390010A0CB /* Reduce.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F31E2AB0D6380010A0CB /* Reduce.swift */; }; + 8E63F3662AB0D6390010A0CB /* Catch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F31F2AB0D6380010A0CB /* Catch.swift */; }; + 8E63F3672AB0D6390010A0CB /* Just.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3202AB0D6380010A0CB /* Just.swift */; }; + 8E63F3682AB0D6390010A0CB /* Repeat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3212AB0D6380010A0CB /* Repeat.swift */; }; + 8E63F3692AB0D6390010A0CB /* Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3222AB0D6380010A0CB /* Zip+arity.swift */; }; + 8E63F36A2AB0D6390010A0CB /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3232AB0D6380010A0CB /* Map.swift */; }; + 8E63F36B2AB0D6390010A0CB /* TakeWithPredicate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3242AB0D6380010A0CB /* TakeWithPredicate.swift */; }; + 8E63F36C2AB0D6390010A0CB /* Timer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3252AB0D6380010A0CB /* Timer.swift */; }; + 8E63F36D2AB0D6390010A0CB /* SkipUntil.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3262AB0D6380010A0CB /* SkipUntil.swift */; }; + 8E63F36E2AB0D6390010A0CB /* Multicast.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3272AB0D6380010A0CB /* Multicast.swift */; }; + 8E63F36F2AB0D6390010A0CB /* AsMaybe.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F3292AB0D6380010A0CB /* AsMaybe.swift */; }; + 8E63F3702AB0D6390010A0CB /* ToArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E63F32A2AB0D6380010A0CB /* ToArray.swift */; }; + 8EF49F392AB1CCF30019E5F9 /* Array+Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EF49F382AB1CCF30019E5F9 /* Array+Utils.swift */; }; + 8EF49F3B2AB1CD3E0019E5F9 /* CBCentral+Uuid.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EF49F3A2AB1CD3E0019E5F9 /* CBCentral+Uuid.swift */; }; + 8EF49F3D2AB1CD720019E5F9 /* CBCentralManagerDelegateWrapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EF49F3C2AB1CD720019E5F9 /* CBCentralManagerDelegateWrapper.swift */; }; + 8EF49F412AB1CDDE0019E5F9 /* CBPeripheralDelegateWrapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EF49F402AB1CDDE0019E5F9 /* CBPeripheralDelegateWrapper.swift */; }; + 8EF49F492AB1CE400019E5F9 /* ManagerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EF49F482AB1CE400019E5F9 /* ManagerType.swift */; }; + 8EFF12592AB0C09600399069 /* Disposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11E92AB0C09500399069 /* Disposable.swift */; }; + 8EFF125A2AB0C09600399069 /* Date+Dispatch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11EA2AB0C09500399069 /* Date+Dispatch.swift */; }; + 8EFF125B2AB0C09600399069 /* Event.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11EB2AB0C09500399069 /* Event.swift */; }; + 8EFF125C2AB0C09600399069 /* Cancelable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11EC2AB0C09500399069 /* Cancelable.swift */; }; + 8EFF125D2AB0C09600399069 /* DisposeBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11EE2AB0C09500399069 /* DisposeBase.swift */; }; + 8EFF125E2AB0C09600399069 /* DisposeBag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11EF2AB0C09500399069 /* DisposeBag.swift */; }; + 8EFF125F2AB0C09600399069 /* ScheduledDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11F02AB0C09500399069 /* ScheduledDisposable.swift */; }; + 8EFF12602AB0C09600399069 /* NopDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11F12AB0C09500399069 /* NopDisposable.swift */; }; + 8EFF12612AB0C09600399069 /* SubscriptionDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11F22AB0C09500399069 /* SubscriptionDisposable.swift */; }; + 8EFF12622AB0C09600399069 /* RefCountDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11F32AB0C09500399069 /* RefCountDisposable.swift */; }; + 8EFF12632AB0C09600399069 /* CompositeDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11F42AB0C09500399069 /* CompositeDisposable.swift */; }; + 8EFF12642AB0C09600399069 /* SingleAssignmentDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11F52AB0C09500399069 /* SingleAssignmentDisposable.swift */; }; + 8EFF12652AB0C09600399069 /* SerialDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11F62AB0C09500399069 /* SerialDisposable.swift */; }; + 8EFF12662AB0C09600399069 /* BinaryDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11F72AB0C09500399069 /* BinaryDisposable.swift */; }; + 8EFF12672AB0C09600399069 /* AnonymousDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11F82AB0C09500399069 /* AnonymousDisposable.swift */; }; + 8EFF12682AB0C09600399069 /* BooleanDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11F92AB0C09500399069 /* BooleanDisposable.swift */; }; + 8EFF12692AB0C09600399069 /* Disposables.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11FA2AB0C09500399069 /* Disposables.swift */; }; + 8EFF126A2AB0C09600399069 /* Errors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF11FB2AB0C09500399069 /* Errors.swift */; }; + 8EFF12B12AB0C09600399069 /* ObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12452AB0C09500399069 /* ObservableType.swift */; }; + 8EFF12B22AB0C09600399069 /* LockOwnerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12472AB0C09500399069 /* LockOwnerType.swift */; }; + 8EFF12B32AB0C09600399069 /* SynchronizedDisposeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12482AB0C09500399069 /* SynchronizedDisposeType.swift */; }; + 8EFF12B42AB0C09600399069 /* SynchronizedOnType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12492AB0C09500399069 /* SynchronizedOnType.swift */; }; + 8EFF12B52AB0C09600399069 /* Lock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF124A2AB0C09500399069 /* Lock.swift */; }; + 8EFF12B62AB0C09600399069 /* AsyncLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF124B2AB0C09500399069 /* AsyncLock.swift */; }; + 8EFF12B72AB0C09600399069 /* SynchronizedUnsubscribeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF124C2AB0C09500399069 /* SynchronizedUnsubscribeType.swift */; }; + 8EFF12B82AB0C09600399069 /* Observable+Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF124E2AB0C09500399069 /* Observable+Concurrency.swift */; }; + 8EFF12B92AB0C09600399069 /* ImmediateSchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF124F2AB0C09500399069 /* ImmediateSchedulerType.swift */; }; + 8EFF12BA2AB0C09600399069 /* ObservableType+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12502AB0C09500399069 /* ObservableType+Extensions.swift */; }; + 8EFF12BB2AB0C09600399069 /* Bag+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12522AB0C09600399069 /* Bag+Rx.swift */; }; + 8EFF12BC2AB0C09600399069 /* AnyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12532AB0C09600399069 /* AnyObserver.swift */; }; + 8EFF12BD2AB0C09600399069 /* Observable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12542AB0C09600399069 /* Observable.swift */; }; + 8EFF12BE2AB0C09600399069 /* Binder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12552AB0C09600399069 /* Binder.swift */; }; + 8EFF12BF2AB0C09600399069 /* GroupedObservable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12562AB0C09600399069 /* GroupedObservable.swift */; }; + 8EFF12C02AB0C09600399069 /* ObservableConvertibleType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12572AB0C09600399069 /* ObservableConvertibleType.swift */; }; + 8EFF12C12AB0C09600399069 /* ConnectableObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12582AB0C09600399069 /* ConnectableObservableType.swift */; }; + 8EFF12C72AB0C0A200399069 /* ObserverType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12C22AB0C0A200399069 /* ObserverType.swift */; }; + 8EFF12C82AB0C0A200399069 /* ObserverBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12C42AB0C0A200399069 /* ObserverBase.swift */; }; + 8EFF12C92AB0C0A200399069 /* TailRecursiveSink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12C52AB0C0A200399069 /* TailRecursiveSink.swift */; }; + 8EFF12CA2AB0C0A200399069 /* AnonymousObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12C62AB0C0A200399069 /* AnonymousObserver.swift */; }; + 8EFF12E22AB0C0F200399069 /* Completable+AndThen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12CD2AB0C0F200399069 /* Completable+AndThen.swift */; }; + 8EFF12E32AB0C0F200399069 /* Completable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12CF2AB0C0F200399069 /* Completable.swift */; }; + 8EFF12E42AB0C0F200399069 /* Single.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12D02AB0C0F200399069 /* Single.swift */; }; + 8EFF12E52AB0C0F200399069 /* PrimitiveSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12D12AB0C0F200399069 /* PrimitiveSequence.swift */; }; + 8EFF12E62AB0C0F200399069 /* Maybe.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12D22AB0C0F200399069 /* Maybe.swift */; }; + 8EFF12E72AB0C0F200399069 /* ObservableType+PrimitiveSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12D32AB0C0F200399069 /* ObservableType+PrimitiveSequence.swift */; }; + 8EFF12E82AB0C0F200399069 /* PrimitiveSequence+Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12D42AB0C0F200399069 /* PrimitiveSequence+Zip+arity.swift */; }; + 8EFF12E92AB0C0F200399069 /* PrimitiveSequence+Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12D52AB0C0F200399069 /* PrimitiveSequence+Concurrency.swift */; }; + 8EFF12EA2AB0C0F200399069 /* Infallible+Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12D72AB0C0F200399069 /* Infallible+Zip+arity.swift */; }; + 8EFF12EB2AB0C0F200399069 /* Infallible+Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12D82AB0C0F200399069 /* Infallible+Concurrency.swift */; }; + 8EFF12EC2AB0C0F200399069 /* Infallible+Create.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12DA2AB0C0F200399069 /* Infallible+Create.swift */; }; + 8EFF12ED2AB0C0F200399069 /* Infallible+Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12DB2AB0C0F200399069 /* Infallible+Operators.swift */; }; + 8EFF12EE2AB0C0F200399069 /* Infallible+Debug.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12DC2AB0C0F200399069 /* Infallible+Debug.swift */; }; + 8EFF12EF2AB0C0F200399069 /* Infallible+CombineLatest+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12DE2AB0C0F200399069 /* Infallible+CombineLatest+arity.swift */; }; + 8EFF12F02AB0C0F200399069 /* Infallible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12DF2AB0C0F200399069 /* Infallible.swift */; }; + 8EFF12F12AB0C0F200399069 /* Infallible+CombineLatest+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12E02AB0C0F200399069 /* Infallible+CombineLatest+Collection.swift */; }; + 8EFF12F22AB0C0F200399069 /* ObservableConvertibleType+Infallible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12E12AB0C0F200399069 /* ObservableConvertibleType+Infallible.swift */; }; + 8EFF12F52AB0C0FF00399069 /* SwiftSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12F42AB0C0FF00399069 /* SwiftSupport.swift */; }; + 8EFF12FC2AB0C10D00399069 /* SubjectType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12F72AB0C10D00399069 /* SubjectType.swift */; }; + 8EFF12FD2AB0C10D00399069 /* BehaviorSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12F82AB0C10D00399069 /* BehaviorSubject.swift */; }; + 8EFF12FE2AB0C10D00399069 /* AsyncSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12F92AB0C10D00399069 /* AsyncSubject.swift */; }; + 8EFF12FF2AB0C10D00399069 /* ReplaySubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12FA2AB0C10D00399069 /* ReplaySubject.swift */; }; + 8EFF13002AB0C10D00399069 /* PublishSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF12FB2AB0C10D00399069 /* PublishSubject.swift */; }; + 8EFF13142AB0C15500399069 /* RecursiveScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF13022AB0C15500399069 /* RecursiveScheduler.swift */; }; + 8EFF13152AB0C15500399069 /* OperationQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF13032AB0C15500399069 /* OperationQueueScheduler.swift */; }; + 8EFF13162AB0C15500399069 /* VirtualTimeScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF13042AB0C15500399069 /* VirtualTimeScheduler.swift */; }; + 8EFF13172AB0C15500399069 /* SchedulerServices+Emulation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF13052AB0C15500399069 /* SchedulerServices+Emulation.swift */; }; + 8EFF13182AB0C15500399069 /* CurrentThreadScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF13062AB0C15500399069 /* CurrentThreadScheduler.swift */; }; + 8EFF13192AB0C15500399069 /* MainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF13072AB0C15500399069 /* MainScheduler.swift */; }; + 8EFF131A2AB0C15500399069 /* ConcurrentDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF13082AB0C15500399069 /* ConcurrentDispatchQueueScheduler.swift */; }; + 8EFF131B2AB0C15500399069 /* ScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF130A2AB0C15500399069 /* ScheduledItem.swift */; }; + 8EFF131C2AB0C15500399069 /* InvocableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF130B2AB0C15500399069 /* InvocableType.swift */; }; + 8EFF131D2AB0C15500399069 /* InvocableScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF130C2AB0C15500399069 /* InvocableScheduledItem.swift */; }; + 8EFF131E2AB0C15500399069 /* DispatchQueueConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF130D2AB0C15500399069 /* DispatchQueueConfiguration.swift */; }; + 8EFF131F2AB0C15500399069 /* ScheduledItemType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF130E2AB0C15500399069 /* ScheduledItemType.swift */; }; + 8EFF13202AB0C15500399069 /* ConcurrentMainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF130F2AB0C15500399069 /* ConcurrentMainScheduler.swift */; }; + 8EFF13212AB0C15500399069 /* SerialDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF13102AB0C15500399069 /* SerialDispatchQueueScheduler.swift */; }; + 8EFF13222AB0C15500399069 /* HistoricalScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF13112AB0C15500399069 /* HistoricalScheduler.swift */; }; + 8EFF13232AB0C15500399069 /* VirtualTimeConverterType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF13122AB0C15500399069 /* VirtualTimeConverterType.swift */; }; + 8EFF13242AB0C15500399069 /* HistoricalSchedulerTimeConverter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF13132AB0C15500399069 /* HistoricalSchedulerTimeConverter.swift */; }; + 8EFF133C2AB0C17800399069 /* RxMutableBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF13392AB0C17800399069 /* RxMutableBox.swift */; }; + 8EFF133D2AB0C17800399069 /* Reactive.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF133A2AB0C17800399069 /* Reactive.swift */; }; + 8EFF133E2AB0C17800399069 /* Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF133B2AB0C17800399069 /* Rx.swift */; }; + 8EFF13402AB0C21F00399069 /* SchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EFF133F2AB0C21F00399069 /* SchedulerType.swift */; }; + A8F13C2A2316ADE700A70E91 /* MultiPlatformBLEAdapter.m in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C292316ADE700A70E91 /* MultiPlatformBLEAdapter.m */; }; + A8F13C2B2316ADE700A70E91 /* MultiPlatformBLEAdapter.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = A8F13C282316ADE700A70E91 /* MultiPlatformBLEAdapter.h */; }; + A8F13D072316AF7600A70E91 /* RxCBCharacteristic.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C442316AF7600A70E91 /* RxCBCharacteristic.swift */; }; + A8F13D082316AF7600A70E91 /* RxCBService.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C452316AF7600A70E91 /* RxCBService.swift */; }; + A8F13D092316AF7600A70E91 /* RxDescriptorType.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C462316AF7600A70E91 /* RxDescriptorType.swift */; }; + A8F13D0A2316AF7600A70E91 /* BluetoothState.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C472316AF7600A70E91 /* BluetoothState.swift */; }; + A8F13D0B2316AF7600A70E91 /* Peripheral.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C482316AF7600A70E91 /* Peripheral.swift */; }; + A8F13D0C2316AF7600A70E91 /* Logging.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C492316AF7600A70E91 /* Logging.swift */; }; + A8F13D0D2316AF7600A70E91 /* RxCharacteristicType.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C4A2316AF7600A70E91 /* RxCharacteristicType.swift */; }; + A8F13D0E2316AF7600A70E91 /* DeviceIdentifiers.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C4B2316AF7600A70E91 /* DeviceIdentifiers.swift */; }; + A8F13D0F2316AF7600A70E91 /* Service.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C4C2316AF7600A70E91 /* Service.swift */; }; + A8F13D102316AF7600A70E91 /* RxServiceType.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C4D2316AF7600A70E91 /* RxServiceType.swift */; }; + A8F13D112316AF7600A70E91 /* BluetoothManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C4E2316AF7600A70E91 /* BluetoothManager.swift */; }; + A8F13D122316AF7600A70E91 /* BluetoothError.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C4F2316AF7600A70E91 /* BluetoothError.swift */; }; + A8F13D132316AF7600A70E91 /* Peripheral+Convenience.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C502316AF7600A70E91 /* Peripheral+Convenience.swift */; }; + A8F13D142316AF7600A70E91 /* AdvertisementData.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C512316AF7600A70E91 /* AdvertisementData.swift */; }; + A8F13D152316AF7600A70E91 /* RxCentralManagerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C532316AF7600A70E91 /* RxCentralManagerType.swift */; }; + A8F13D162316AF7600A70E91 /* RxCBCentralManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C542316AF7600A70E91 /* RxCBCentralManager.swift */; }; + A8F13D172316AF7600A70E91 /* RestoredState.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C552316AF7600A70E91 /* RestoredState.swift */; }; + A8F13D182316AF7600A70E91 /* Descriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C562316AF7600A70E91 /* Descriptor.swift */; }; + A8F13D192316AF7600A70E91 /* Boxes.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C572316AF7600A70E91 /* Boxes.swift */; }; + A8F13D1A2316AF7600A70E91 /* RxCBDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C582316AF7600A70E91 /* RxCBDescriptor.swift */; }; + A8F13D1B2316AF7600A70E91 /* Observable+Absorb.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C592316AF7600A70E91 /* Observable+Absorb.swift */; }; + A8F13D1C2316AF7600A70E91 /* UUIDIdentifiable.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C5A2316AF7600A70E91 /* UUIDIdentifiable.swift */; }; + A8F13D1D2316AF7600A70E91 /* ScanOperation.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C5B2316AF7600A70E91 /* ScanOperation.swift */; }; + A8F13D1E2316AF7600A70E91 /* ScannedPeripheral.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C5C2316AF7600A70E91 /* ScannedPeripheral.swift */; }; + A8F13D1F2316AF7600A70E91 /* Observable+QueueSubscribeOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C5D2316AF7600A70E91 /* Observable+QueueSubscribeOn.swift */; }; + A8F13D202316AF7600A70E91 /* Characteristic.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C5E2316AF7600A70E91 /* Characteristic.swift */; }; + A8F13D212316AF7600A70E91 /* Unimplemented.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C5F2316AF7600A70E91 /* Unimplemented.swift */; }; + A8F13D222316AF7600A70E91 /* RxCBPeripheral.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C602316AF7600A70E91 /* RxCBPeripheral.swift */; }; + A8F13D232316AF7600A70E91 /* RxPeripheralType.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13C612316AF7600A70E91 /* RxPeripheralType.swift */; }; + A8F13DFB2316BDFB00A70E91 /* BleEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13DF52316BDFA00A70E91 /* BleEvent.swift */; }; + A8F13DFC2316BDFB00A70E91 /* BleError.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13DF62316BDFA00A70E91 /* BleError.swift */; }; + A8F13DFD2316BDFB00A70E91 /* BleUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13DF72316BDFA00A70E91 /* BleUtils.swift */; }; + A8F13DFE2316BDFB00A70E91 /* BleExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13DF82316BDFA00A70E91 /* BleExtensions.swift */; }; + A8F13DFF2316BDFB00A70E91 /* BleModule.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13DFA2316BDFB00A70E91 /* BleModule.swift */; }; + A8F13E042316BE2F00A70E91 /* DisposableMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13E022316BE2F00A70E91 /* DisposableMap.swift */; }; + A8F13E052316BE2F00A70E91 /* SafePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F13E032316BE2F00A70E91 /* SafePromise.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXCopyFilesBuildPhase section */ + A8F13C232316ADE700A70E91 /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = "include/$(PRODUCT_NAME)"; + dstSubfolderSpec = 16; + files = ( + A8F13C2B2316ADE700A70E91 /* MultiPlatformBLEAdapter.h in CopyFiles */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 816FE39A234F29B3008BF70D /* BleAdapterFactory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BleAdapterFactory.swift; sourceTree = ""; }; + 81B95B91234B256000D96D28 /* BleAdapter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BleAdapter.swift; sourceTree = ""; }; + 8E63F2D02AB0CE9B0010A0CB /* AtomicInt.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AtomicInt.swift; sourceTree = ""; }; + 8E63F2D22AB0CEEC0010A0CB /* DispatchQueue+Extensions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DispatchQueue+Extensions.swift"; sourceTree = ""; }; + 8E63F2D42AB0CF050010A0CB /* Platform.Darwin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Platform.Darwin.swift; sourceTree = ""; }; + 8E63F2D62AB0CF1E0010A0CB /* Platform.Linux.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Platform.Linux.swift; sourceTree = ""; }; + 8E63F2D82AB0CF400010A0CB /* RecursiveLock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecursiveLock.swift; sourceTree = ""; }; + 8E63F2DA2AB0CF730010A0CB /* Bag.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Bag.swift; sourceTree = ""; }; + 8E63F2DC2AB0CF830010A0CB /* InfiniteSequence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InfiniteSequence.swift; sourceTree = ""; }; + 8E63F2DE2AB0CFB10010A0CB /* PriorityQueue.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PriorityQueue.swift; sourceTree = ""; }; + 8E63F2E02AB0CFC30010A0CB /* Queue.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Queue.swift; sourceTree = ""; }; + 8E63F2E32AB0D6340010A0CB /* DefaultIfEmpty.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DefaultIfEmpty.swift; sourceTree = ""; }; + 8E63F2E42AB0D6340010A0CB /* Never.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Never.swift; sourceTree = ""; }; + 8E63F2E52AB0D6340010A0CB /* CombineLatest+arity.tt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "CombineLatest+arity.tt"; sourceTree = ""; }; + 8E63F2E62AB0D6340010A0CB /* GroupBy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GroupBy.swift; sourceTree = ""; }; + 8E63F2E72AB0D6340010A0CB /* Switch.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Switch.swift; sourceTree = ""; }; + 8E63F2E82AB0D6340010A0CB /* WithUnretained.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WithUnretained.swift; sourceTree = ""; }; + 8E63F2E92AB0D6340010A0CB /* Producer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Producer.swift; sourceTree = ""; }; + 8E63F2EA2AB0D6340010A0CB /* RetryWhen.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RetryWhen.swift; sourceTree = ""; }; + 8E63F2EB2AB0D6340010A0CB /* StartWith.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StartWith.swift; sourceTree = ""; }; + 8E63F2EC2AB0D6340010A0CB /* Scan.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Scan.swift; sourceTree = ""; }; + 8E63F2ED2AB0D6350010A0CB /* Using.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Using.swift; sourceTree = ""; }; + 8E63F2EE2AB0D6350010A0CB /* Concat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Concat.swift; sourceTree = ""; }; + 8E63F2EF2AB0D6350010A0CB /* Do.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Do.swift; sourceTree = ""; }; + 8E63F2F02AB0D6350010A0CB /* SwitchIfEmpty.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwitchIfEmpty.swift; sourceTree = ""; }; + 8E63F2F12AB0D6350010A0CB /* Throttle.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Throttle.swift; sourceTree = ""; }; + 8E63F2F22AB0D6350010A0CB /* WithLatestFrom.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WithLatestFrom.swift; sourceTree = ""; }; + 8E63F2F32AB0D6350010A0CB /* Debounce.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Debounce.swift; sourceTree = ""; }; + 8E63F2F42AB0D6350010A0CB /* Deferred.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Deferred.swift; sourceTree = ""; }; + 8E63F2F52AB0D6350010A0CB /* Enumerated.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Enumerated.swift; sourceTree = ""; }; + 8E63F2F62AB0D6350010A0CB /* Buffer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Buffer.swift; sourceTree = ""; }; + 8E63F2F72AB0D6350010A0CB /* Range.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Range.swift; sourceTree = ""; }; + 8E63F2F82AB0D6350010A0CB /* Sequence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Sequence.swift; sourceTree = ""; }; + 8E63F2F92AB0D6350010A0CB /* SkipWhile.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SkipWhile.swift; sourceTree = ""; }; + 8E63F2FA2AB0D6350010A0CB /* ObserveOn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ObserveOn.swift; sourceTree = ""; }; + 8E63F2FB2AB0D6350010A0CB /* ElementAt.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ElementAt.swift; sourceTree = ""; }; + 8E63F2FC2AB0D6350010A0CB /* Filter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Filter.swift; sourceTree = ""; }; + 8E63F2FD2AB0D6350010A0CB /* SingleAsync.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SingleAsync.swift; sourceTree = ""; }; + 8E63F2FE2AB0D6350010A0CB /* Timeout.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Timeout.swift; sourceTree = ""; }; + 8E63F2FF2AB0D6360010A0CB /* AddRef.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AddRef.swift; sourceTree = ""; }; + 8E63F3002AB0D6360010A0CB /* AsSingle.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AsSingle.swift; sourceTree = ""; }; + 8E63F3012AB0D6360010A0CB /* CombineLatest+Collection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "CombineLatest+Collection.swift"; sourceTree = ""; }; + 8E63F3022AB0D6360010A0CB /* Decode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Decode.swift; sourceTree = ""; }; + 8E63F3032AB0D6360010A0CB /* Window.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Window.swift; sourceTree = ""; }; + 8E63F3042AB0D6360010A0CB /* CompactMap.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompactMap.swift; sourceTree = ""; }; + 8E63F3052AB0D6360010A0CB /* DelaySubscription.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DelaySubscription.swift; sourceTree = ""; }; + 8E63F3062AB0D6360010A0CB /* DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DistinctUntilChanged.swift; sourceTree = ""; }; + 8E63F3072AB0D6360010A0CB /* First.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = First.swift; sourceTree = ""; }; + 8E63F3082AB0D6360010A0CB /* Amb.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Amb.swift; sourceTree = ""; }; + 8E63F3092AB0D6360010A0CB /* Error.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Error.swift; sourceTree = ""; }; + 8E63F30A2AB0D6360010A0CB /* Generate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Generate.swift; sourceTree = ""; }; + 8E63F30B2AB0D6370010A0CB /* Materialize.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Materialize.swift; sourceTree = ""; }; + 8E63F30C2AB0D6370010A0CB /* SubscribeOn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SubscribeOn.swift; sourceTree = ""; }; + 8E63F30D2AB0D6370010A0CB /* Debug.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Debug.swift; sourceTree = ""; }; + 8E63F30E2AB0D6370010A0CB /* Create.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Create.swift; sourceTree = ""; }; + 8E63F30F2AB0D6370010A0CB /* Sample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Sample.swift; sourceTree = ""; }; + 8E63F3102AB0D6370010A0CB /* Take.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Take.swift; sourceTree = ""; }; + 8E63F3112AB0D6370010A0CB /* Merge.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Merge.swift; sourceTree = ""; }; + 8E63F3122AB0D6370010A0CB /* Empty.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Empty.swift; sourceTree = ""; }; + 8E63F3132AB0D6370010A0CB /* Dematerialize.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Dematerialize.swift; sourceTree = ""; }; + 8E63F3142AB0D6370010A0CB /* Zip.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Zip.swift; sourceTree = ""; }; + 8E63F3152AB0D6370010A0CB /* CombineLatest+arity.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "CombineLatest+arity.swift"; sourceTree = ""; }; + 8E63F3162AB0D6370010A0CB /* Skip.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Skip.swift; sourceTree = ""; }; + 8E63F3172AB0D6370010A0CB /* TakeLast.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TakeLast.swift; sourceTree = ""; }; + 8E63F3182AB0D6370010A0CB /* CombineLatest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CombineLatest.swift; sourceTree = ""; }; + 8E63F3192AB0D6370010A0CB /* Zip+Collection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Zip+Collection.swift"; sourceTree = ""; }; + 8E63F31A2AB0D6370010A0CB /* ShareReplayScope.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ShareReplayScope.swift; sourceTree = ""; }; + 8E63F31B2AB0D6380010A0CB /* Sink.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Sink.swift; sourceTree = ""; }; + 8E63F31C2AB0D6380010A0CB /* Delay.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Delay.swift; sourceTree = ""; }; + 8E63F31D2AB0D6380010A0CB /* Optional.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Optional.swift; sourceTree = ""; }; + 8E63F31E2AB0D6380010A0CB /* Reduce.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Reduce.swift; sourceTree = ""; }; + 8E63F31F2AB0D6380010A0CB /* Catch.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Catch.swift; sourceTree = ""; }; + 8E63F3202AB0D6380010A0CB /* Just.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Just.swift; sourceTree = ""; }; + 8E63F3212AB0D6380010A0CB /* Repeat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Repeat.swift; sourceTree = ""; }; + 8E63F3222AB0D6380010A0CB /* Zip+arity.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Zip+arity.swift"; sourceTree = ""; }; + 8E63F3232AB0D6380010A0CB /* Map.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = ""; }; + 8E63F3242AB0D6380010A0CB /* TakeWithPredicate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TakeWithPredicate.swift; sourceTree = ""; }; + 8E63F3252AB0D6380010A0CB /* Timer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Timer.swift; sourceTree = ""; }; + 8E63F3262AB0D6380010A0CB /* SkipUntil.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SkipUntil.swift; sourceTree = ""; }; + 8E63F3272AB0D6380010A0CB /* Multicast.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Multicast.swift; sourceTree = ""; }; + 8E63F3282AB0D6380010A0CB /* Zip+arity.tt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "Zip+arity.tt"; sourceTree = ""; }; + 8E63F3292AB0D6380010A0CB /* AsMaybe.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AsMaybe.swift; sourceTree = ""; }; + 8E63F32A2AB0D6380010A0CB /* ToArray.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ToArray.swift; sourceTree = ""; }; + 8EF49F382AB1CCF30019E5F9 /* Array+Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Array+Utils.swift"; sourceTree = ""; }; + 8EF49F3A2AB1CD3E0019E5F9 /* CBCentral+Uuid.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "CBCentral+Uuid.swift"; sourceTree = ""; }; + 8EF49F3C2AB1CD720019E5F9 /* CBCentralManagerDelegateWrapper.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CBCentralManagerDelegateWrapper.swift; sourceTree = ""; }; + 8EF49F402AB1CDDE0019E5F9 /* CBPeripheralDelegateWrapper.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CBPeripheralDelegateWrapper.swift; sourceTree = ""; }; + 8EF49F482AB1CE400019E5F9 /* ManagerType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ManagerType.swift; sourceTree = ""; }; + 8EFF11E92AB0C09500399069 /* Disposable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Disposable.swift; sourceTree = ""; }; + 8EFF11EA2AB0C09500399069 /* Date+Dispatch.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = "Date+Dispatch.swift"; path = "../../../Downloads/RxSwift-6.6.0 6/RxSwift/Date+Dispatch.swift"; sourceTree = ""; }; + 8EFF11EB2AB0C09500399069 /* Event.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Event.swift; sourceTree = ""; }; + 8EFF11EC2AB0C09500399069 /* Cancelable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cancelable.swift; sourceTree = ""; }; + 8EFF11EE2AB0C09500399069 /* DisposeBase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DisposeBase.swift; sourceTree = ""; }; + 8EFF11EF2AB0C09500399069 /* DisposeBag.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DisposeBag.swift; sourceTree = ""; }; + 8EFF11F02AB0C09500399069 /* ScheduledDisposable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ScheduledDisposable.swift; sourceTree = ""; }; + 8EFF11F12AB0C09500399069 /* NopDisposable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NopDisposable.swift; sourceTree = ""; }; + 8EFF11F22AB0C09500399069 /* SubscriptionDisposable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SubscriptionDisposable.swift; sourceTree = ""; }; + 8EFF11F32AB0C09500399069 /* RefCountDisposable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RefCountDisposable.swift; sourceTree = ""; }; + 8EFF11F42AB0C09500399069 /* CompositeDisposable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompositeDisposable.swift; sourceTree = ""; }; + 8EFF11F52AB0C09500399069 /* SingleAssignmentDisposable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SingleAssignmentDisposable.swift; sourceTree = ""; }; + 8EFF11F62AB0C09500399069 /* SerialDisposable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerialDisposable.swift; sourceTree = ""; }; + 8EFF11F72AB0C09500399069 /* BinaryDisposable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BinaryDisposable.swift; sourceTree = ""; }; + 8EFF11F82AB0C09500399069 /* AnonymousDisposable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnonymousDisposable.swift; sourceTree = ""; }; + 8EFF11F92AB0C09500399069 /* BooleanDisposable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BooleanDisposable.swift; sourceTree = ""; }; + 8EFF11FA2AB0C09500399069 /* Disposables.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Disposables.swift; sourceTree = ""; }; + 8EFF11FB2AB0C09500399069 /* Errors.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Errors.swift; sourceTree = ""; }; + 8EFF12452AB0C09500399069 /* ObservableType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ObservableType.swift; sourceTree = ""; }; + 8EFF12472AB0C09500399069 /* LockOwnerType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockOwnerType.swift; sourceTree = ""; }; + 8EFF12482AB0C09500399069 /* SynchronizedDisposeType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SynchronizedDisposeType.swift; sourceTree = ""; }; + 8EFF12492AB0C09500399069 /* SynchronizedOnType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SynchronizedOnType.swift; sourceTree = ""; }; + 8EFF124A2AB0C09500399069 /* Lock.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Lock.swift; sourceTree = ""; }; + 8EFF124B2AB0C09500399069 /* AsyncLock.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AsyncLock.swift; sourceTree = ""; }; + 8EFF124C2AB0C09500399069 /* SynchronizedUnsubscribeType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SynchronizedUnsubscribeType.swift; sourceTree = ""; }; + 8EFF124D2AB0C09500399069 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = "../../../Downloads/RxSwift-6.6.0 6/RxSwift/Info.plist"; sourceTree = ""; }; + 8EFF124E2AB0C09500399069 /* Observable+Concurrency.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = "Observable+Concurrency.swift"; path = "../../../Downloads/RxSwift-6.6.0 6/RxSwift/Observable+Concurrency.swift"; sourceTree = ""; }; + 8EFF124F2AB0C09500399069 /* ImmediateSchedulerType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ImmediateSchedulerType.swift; sourceTree = ""; }; + 8EFF12502AB0C09500399069 /* ObservableType+Extensions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ObservableType+Extensions.swift"; sourceTree = ""; }; + 8EFF12522AB0C09600399069 /* Bag+Rx.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Bag+Rx.swift"; sourceTree = ""; }; + 8EFF12532AB0C09600399069 /* AnyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyObserver.swift; sourceTree = ""; }; + 8EFF12542AB0C09600399069 /* Observable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Observable.swift; sourceTree = ""; }; + 8EFF12552AB0C09600399069 /* Binder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Binder.swift; path = "../../../Downloads/RxSwift-6.6.0 6/RxSwift/Binder.swift"; sourceTree = ""; }; + 8EFF12562AB0C09600399069 /* GroupedObservable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GroupedObservable.swift; sourceTree = ""; }; + 8EFF12572AB0C09600399069 /* ObservableConvertibleType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ObservableConvertibleType.swift; sourceTree = ""; }; + 8EFF12582AB0C09600399069 /* ConnectableObservableType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ConnectableObservableType.swift; sourceTree = ""; }; + 8EFF12C22AB0C0A200399069 /* ObserverType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ObserverType.swift; sourceTree = ""; }; + 8EFF12C42AB0C0A200399069 /* ObserverBase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ObserverBase.swift; sourceTree = ""; }; + 8EFF12C52AB0C0A200399069 /* TailRecursiveSink.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TailRecursiveSink.swift; sourceTree = ""; }; + 8EFF12C62AB0C0A200399069 /* AnonymousObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnonymousObserver.swift; sourceTree = ""; }; + 8EFF12CD2AB0C0F200399069 /* Completable+AndThen.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Completable+AndThen.swift"; sourceTree = ""; }; + 8EFF12CE2AB0C0F200399069 /* PrimitiveSequence+Zip+arity.tt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "PrimitiveSequence+Zip+arity.tt"; sourceTree = ""; }; + 8EFF12CF2AB0C0F200399069 /* Completable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Completable.swift; sourceTree = ""; }; + 8EFF12D02AB0C0F200399069 /* Single.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Single.swift; sourceTree = ""; }; + 8EFF12D12AB0C0F200399069 /* PrimitiveSequence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrimitiveSequence.swift; sourceTree = ""; }; + 8EFF12D22AB0C0F200399069 /* Maybe.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Maybe.swift; sourceTree = ""; }; + 8EFF12D32AB0C0F200399069 /* ObservableType+PrimitiveSequence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ObservableType+PrimitiveSequence.swift"; sourceTree = ""; }; + 8EFF12D42AB0C0F200399069 /* PrimitiveSequence+Zip+arity.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PrimitiveSequence+Zip+arity.swift"; sourceTree = ""; }; + 8EFF12D52AB0C0F200399069 /* PrimitiveSequence+Concurrency.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PrimitiveSequence+Concurrency.swift"; sourceTree = ""; }; + 8EFF12D72AB0C0F200399069 /* Infallible+Zip+arity.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Infallible+Zip+arity.swift"; sourceTree = ""; }; + 8EFF12D82AB0C0F200399069 /* Infallible+Concurrency.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Infallible+Concurrency.swift"; sourceTree = ""; }; + 8EFF12D92AB0C0F200399069 /* Infallible+Zip+arity.tt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "Infallible+Zip+arity.tt"; sourceTree = ""; }; + 8EFF12DA2AB0C0F200399069 /* Infallible+Create.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Infallible+Create.swift"; sourceTree = ""; }; + 8EFF12DB2AB0C0F200399069 /* Infallible+Operators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Infallible+Operators.swift"; sourceTree = ""; }; + 8EFF12DC2AB0C0F200399069 /* Infallible+Debug.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Infallible+Debug.swift"; sourceTree = ""; }; + 8EFF12DD2AB0C0F200399069 /* Infallible+CombineLatest+arity.tt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = "Infallible+CombineLatest+arity.tt"; sourceTree = ""; }; + 8EFF12DE2AB0C0F200399069 /* Infallible+CombineLatest+arity.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Infallible+CombineLatest+arity.swift"; sourceTree = ""; }; + 8EFF12DF2AB0C0F200399069 /* Infallible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Infallible.swift; sourceTree = ""; }; + 8EFF12E02AB0C0F200399069 /* Infallible+CombineLatest+Collection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Infallible+CombineLatest+Collection.swift"; sourceTree = ""; }; + 8EFF12E12AB0C0F200399069 /* ObservableConvertibleType+Infallible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ObservableConvertibleType+Infallible.swift"; sourceTree = ""; }; + 8EFF12F42AB0C0FF00399069 /* SwiftSupport.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SwiftSupport.swift; sourceTree = ""; }; + 8EFF12F72AB0C10D00399069 /* SubjectType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SubjectType.swift; sourceTree = ""; }; + 8EFF12F82AB0C10D00399069 /* BehaviorSubject.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BehaviorSubject.swift; sourceTree = ""; }; + 8EFF12F92AB0C10D00399069 /* AsyncSubject.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AsyncSubject.swift; sourceTree = ""; }; + 8EFF12FA2AB0C10D00399069 /* ReplaySubject.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReplaySubject.swift; sourceTree = ""; }; + 8EFF12FB2AB0C10D00399069 /* PublishSubject.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PublishSubject.swift; sourceTree = ""; }; + 8EFF13022AB0C15500399069 /* RecursiveScheduler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecursiveScheduler.swift; sourceTree = ""; }; + 8EFF13032AB0C15500399069 /* OperationQueueScheduler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OperationQueueScheduler.swift; sourceTree = ""; }; + 8EFF13042AB0C15500399069 /* VirtualTimeScheduler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VirtualTimeScheduler.swift; sourceTree = ""; }; + 8EFF13052AB0C15500399069 /* SchedulerServices+Emulation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SchedulerServices+Emulation.swift"; sourceTree = ""; }; + 8EFF13062AB0C15500399069 /* CurrentThreadScheduler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CurrentThreadScheduler.swift; sourceTree = ""; }; + 8EFF13072AB0C15500399069 /* MainScheduler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MainScheduler.swift; sourceTree = ""; }; + 8EFF13082AB0C15500399069 /* ConcurrentDispatchQueueScheduler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ConcurrentDispatchQueueScheduler.swift; sourceTree = ""; }; + 8EFF130A2AB0C15500399069 /* ScheduledItem.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ScheduledItem.swift; sourceTree = ""; }; + 8EFF130B2AB0C15500399069 /* InvocableType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InvocableType.swift; sourceTree = ""; }; + 8EFF130C2AB0C15500399069 /* InvocableScheduledItem.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InvocableScheduledItem.swift; sourceTree = ""; }; + 8EFF130D2AB0C15500399069 /* DispatchQueueConfiguration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DispatchQueueConfiguration.swift; sourceTree = ""; }; + 8EFF130E2AB0C15500399069 /* ScheduledItemType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ScheduledItemType.swift; sourceTree = ""; }; + 8EFF130F2AB0C15500399069 /* ConcurrentMainScheduler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ConcurrentMainScheduler.swift; sourceTree = ""; }; + 8EFF13102AB0C15500399069 /* SerialDispatchQueueScheduler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerialDispatchQueueScheduler.swift; sourceTree = ""; }; + 8EFF13112AB0C15500399069 /* HistoricalScheduler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HistoricalScheduler.swift; sourceTree = ""; }; + 8EFF13122AB0C15500399069 /* VirtualTimeConverterType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VirtualTimeConverterType.swift; sourceTree = ""; }; + 8EFF13132AB0C15500399069 /* HistoricalSchedulerTimeConverter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HistoricalSchedulerTimeConverter.swift; sourceTree = ""; }; + 8EFF13392AB0C17800399069 /* RxMutableBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RxMutableBox.swift; sourceTree = ""; }; + 8EFF133A2AB0C17800399069 /* Reactive.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Reactive.swift; sourceTree = ""; }; + 8EFF133B2AB0C17800399069 /* Rx.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Rx.swift; sourceTree = ""; }; + 8EFF133F2AB0C21F00399069 /* SchedulerType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulerType.swift; sourceTree = ""; }; + A8F13C252316ADE700A70E91 /* libMultiPlatformBLEAdapter.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libMultiPlatformBLEAdapter.a; sourceTree = BUILT_PRODUCTS_DIR; }; + A8F13C282316ADE700A70E91 /* MultiPlatformBLEAdapter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MultiPlatformBLEAdapter.h; sourceTree = ""; }; + A8F13C292316ADE700A70E91 /* MultiPlatformBLEAdapter.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MultiPlatformBLEAdapter.m; sourceTree = ""; }; + A8F13C312316AE3600A70E91 /* MultiPlatformBLEAdapter-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "MultiPlatformBLEAdapter-Bridging-Header.h"; sourceTree = ""; }; + A8F13C442316AF7600A70E91 /* RxCBCharacteristic.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RxCBCharacteristic.swift; sourceTree = ""; }; + A8F13C452316AF7600A70E91 /* RxCBService.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RxCBService.swift; sourceTree = ""; }; + A8F13C462316AF7600A70E91 /* RxDescriptorType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RxDescriptorType.swift; sourceTree = ""; }; + A8F13C472316AF7600A70E91 /* BluetoothState.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BluetoothState.swift; sourceTree = ""; }; + A8F13C482316AF7600A70E91 /* Peripheral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Peripheral.swift; sourceTree = ""; }; + A8F13C492316AF7600A70E91 /* Logging.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Logging.swift; sourceTree = ""; }; + A8F13C4A2316AF7600A70E91 /* RxCharacteristicType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RxCharacteristicType.swift; sourceTree = ""; }; + A8F13C4B2316AF7600A70E91 /* DeviceIdentifiers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DeviceIdentifiers.swift; sourceTree = ""; }; + A8F13C4C2316AF7600A70E91 /* Service.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Service.swift; sourceTree = ""; }; + A8F13C4D2316AF7600A70E91 /* RxServiceType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RxServiceType.swift; sourceTree = ""; }; + A8F13C4E2316AF7600A70E91 /* BluetoothManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BluetoothManager.swift; sourceTree = ""; }; + A8F13C4F2316AF7600A70E91 /* BluetoothError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BluetoothError.swift; sourceTree = ""; }; + A8F13C502316AF7600A70E91 /* Peripheral+Convenience.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Peripheral+Convenience.swift"; sourceTree = ""; }; + A8F13C512316AF7600A70E91 /* AdvertisementData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AdvertisementData.swift; sourceTree = ""; }; + A8F13C522316AF7600A70E91 /* RxBluetoothKit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RxBluetoothKit.h; sourceTree = ""; }; + A8F13C532316AF7600A70E91 /* RxCentralManagerType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RxCentralManagerType.swift; sourceTree = ""; }; + A8F13C542316AF7600A70E91 /* RxCBCentralManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RxCBCentralManager.swift; sourceTree = ""; }; + A8F13C552316AF7600A70E91 /* RestoredState.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RestoredState.swift; sourceTree = ""; }; + A8F13C562316AF7600A70E91 /* Descriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Descriptor.swift; sourceTree = ""; }; + A8F13C572316AF7600A70E91 /* Boxes.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Boxes.swift; sourceTree = ""; }; + A8F13C582316AF7600A70E91 /* RxCBDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RxCBDescriptor.swift; sourceTree = ""; }; + A8F13C592316AF7600A70E91 /* Observable+Absorb.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Observable+Absorb.swift"; sourceTree = ""; }; + A8F13C5A2316AF7600A70E91 /* UUIDIdentifiable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UUIDIdentifiable.swift; sourceTree = ""; }; + A8F13C5B2316AF7600A70E91 /* ScanOperation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ScanOperation.swift; sourceTree = ""; }; + A8F13C5C2316AF7600A70E91 /* ScannedPeripheral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ScannedPeripheral.swift; sourceTree = ""; }; + A8F13C5D2316AF7600A70E91 /* Observable+QueueSubscribeOn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Observable+QueueSubscribeOn.swift"; sourceTree = ""; }; + A8F13C5E2316AF7600A70E91 /* Characteristic.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Characteristic.swift; sourceTree = ""; }; + A8F13C5F2316AF7600A70E91 /* Unimplemented.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Unimplemented.swift; sourceTree = ""; }; + A8F13C602316AF7600A70E91 /* RxCBPeripheral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RxCBPeripheral.swift; sourceTree = ""; }; + A8F13C612316AF7600A70E91 /* RxPeripheralType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RxPeripheralType.swift; sourceTree = ""; }; + A8F13DF52316BDFA00A70E91 /* BleEvent.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BleEvent.swift; sourceTree = ""; }; + A8F13DF62316BDFA00A70E91 /* BleError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BleError.swift; sourceTree = ""; }; + A8F13DF72316BDFA00A70E91 /* BleUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BleUtils.swift; sourceTree = ""; }; + A8F13DF82316BDFA00A70E91 /* BleExtensions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BleExtensions.swift; sourceTree = ""; }; + A8F13DF92316BDFB00A70E91 /* BleClientManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BleClientManager.h; sourceTree = ""; }; + A8F13DFA2316BDFB00A70E91 /* BleModule.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BleModule.swift; sourceTree = ""; }; + A8F13E022316BE2F00A70E91 /* DisposableMap.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DisposableMap.swift; sourceTree = ""; }; + A8F13E032316BE2F00A70E91 /* SafePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SafePromise.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + A8F13C222316ADE700A70E91 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 8E63F2CE2AB0CE770010A0CB /* Platform */ = { + isa = PBXGroup; + children = ( + 8E63F2CF2AB0CE830010A0CB /* DataStructures */, + 8E63F2D02AB0CE9B0010A0CB /* AtomicInt.swift */, + 8E63F2D22AB0CEEC0010A0CB /* DispatchQueue+Extensions.swift */, + 8E63F2D42AB0CF050010A0CB /* Platform.Darwin.swift */, + 8E63F2D62AB0CF1E0010A0CB /* Platform.Linux.swift */, + 8E63F2D82AB0CF400010A0CB /* RecursiveLock.swift */, + ); + path = Platform; + sourceTree = ""; + }; + 8E63F2CF2AB0CE830010A0CB /* DataStructures */ = { + isa = PBXGroup; + children = ( + 8E63F2DA2AB0CF730010A0CB /* Bag.swift */, + 8E63F2DC2AB0CF830010A0CB /* InfiniteSequence.swift */, + 8E63F2DE2AB0CFB10010A0CB /* PriorityQueue.swift */, + 8E63F2E02AB0CFC30010A0CB /* Queue.swift */, + ); + path = DataStructures; + sourceTree = ""; + }; + 8E63F2E22AB0D5D60010A0CB /* Observables */ = { + isa = PBXGroup; + children = ( + 8E63F2FF2AB0D6360010A0CB /* AddRef.swift */, + 8E63F3082AB0D6360010A0CB /* Amb.swift */, + 8E63F3292AB0D6380010A0CB /* AsMaybe.swift */, + 8E63F3002AB0D6360010A0CB /* AsSingle.swift */, + 8E63F2F62AB0D6350010A0CB /* Buffer.swift */, + 8E63F31F2AB0D6380010A0CB /* Catch.swift */, + 8E63F3182AB0D6370010A0CB /* CombineLatest.swift */, + 8E63F3152AB0D6370010A0CB /* CombineLatest+arity.swift */, + 8E63F2E52AB0D6340010A0CB /* CombineLatest+arity.tt */, + 8E63F3012AB0D6360010A0CB /* CombineLatest+Collection.swift */, + 8E63F3042AB0D6360010A0CB /* CompactMap.swift */, + 8E63F2EE2AB0D6350010A0CB /* Concat.swift */, + 8E63F30E2AB0D6370010A0CB /* Create.swift */, + 8E63F2F32AB0D6350010A0CB /* Debounce.swift */, + 8E63F30D2AB0D6370010A0CB /* Debug.swift */, + 8E63F3022AB0D6360010A0CB /* Decode.swift */, + 8E63F2E32AB0D6340010A0CB /* DefaultIfEmpty.swift */, + 8E63F2F42AB0D6350010A0CB /* Deferred.swift */, + 8E63F31C2AB0D6380010A0CB /* Delay.swift */, + 8E63F3052AB0D6360010A0CB /* DelaySubscription.swift */, + 8E63F3132AB0D6370010A0CB /* Dematerialize.swift */, + 8E63F3062AB0D6360010A0CB /* DistinctUntilChanged.swift */, + 8E63F2EF2AB0D6350010A0CB /* Do.swift */, + 8E63F2FB2AB0D6350010A0CB /* ElementAt.swift */, + 8E63F3122AB0D6370010A0CB /* Empty.swift */, + 8E63F2F52AB0D6350010A0CB /* Enumerated.swift */, + 8E63F3092AB0D6360010A0CB /* Error.swift */, + 8E63F2FC2AB0D6350010A0CB /* Filter.swift */, + 8E63F3072AB0D6360010A0CB /* First.swift */, + 8E63F30A2AB0D6360010A0CB /* Generate.swift */, + 8E63F2E62AB0D6340010A0CB /* GroupBy.swift */, + 8E63F3202AB0D6380010A0CB /* Just.swift */, + 8E63F3232AB0D6380010A0CB /* Map.swift */, + 8E63F30B2AB0D6370010A0CB /* Materialize.swift */, + 8E63F3112AB0D6370010A0CB /* Merge.swift */, + 8E63F3272AB0D6380010A0CB /* Multicast.swift */, + 8E63F2E42AB0D6340010A0CB /* Never.swift */, + 8E63F2FA2AB0D6350010A0CB /* ObserveOn.swift */, + 8E63F31D2AB0D6380010A0CB /* Optional.swift */, + 8E63F2E92AB0D6340010A0CB /* Producer.swift */, + 8E63F2F72AB0D6350010A0CB /* Range.swift */, + 8E63F31E2AB0D6380010A0CB /* Reduce.swift */, + 8E63F3212AB0D6380010A0CB /* Repeat.swift */, + 8E63F2EA2AB0D6340010A0CB /* RetryWhen.swift */, + 8E63F30F2AB0D6370010A0CB /* Sample.swift */, + 8E63F2EC2AB0D6340010A0CB /* Scan.swift */, + 8E63F2F82AB0D6350010A0CB /* Sequence.swift */, + 8E63F31A2AB0D6370010A0CB /* ShareReplayScope.swift */, + 8E63F2FD2AB0D6350010A0CB /* SingleAsync.swift */, + 8E63F31B2AB0D6380010A0CB /* Sink.swift */, + 8E63F3162AB0D6370010A0CB /* Skip.swift */, + 8E63F3262AB0D6380010A0CB /* SkipUntil.swift */, + 8E63F2F92AB0D6350010A0CB /* SkipWhile.swift */, + 8E63F2EB2AB0D6340010A0CB /* StartWith.swift */, + 8E63F30C2AB0D6370010A0CB /* SubscribeOn.swift */, + 8E63F2E72AB0D6340010A0CB /* Switch.swift */, + 8E63F2F02AB0D6350010A0CB /* SwitchIfEmpty.swift */, + 8E63F3102AB0D6370010A0CB /* Take.swift */, + 8E63F3172AB0D6370010A0CB /* TakeLast.swift */, + 8E63F3242AB0D6380010A0CB /* TakeWithPredicate.swift */, + 8E63F2F12AB0D6350010A0CB /* Throttle.swift */, + 8E63F2FE2AB0D6350010A0CB /* Timeout.swift */, + 8E63F3252AB0D6380010A0CB /* Timer.swift */, + 8E63F32A2AB0D6380010A0CB /* ToArray.swift */, + 8E63F2ED2AB0D6350010A0CB /* Using.swift */, + 8E63F3032AB0D6360010A0CB /* Window.swift */, + 8E63F2F22AB0D6350010A0CB /* WithLatestFrom.swift */, + 8E63F2E82AB0D6340010A0CB /* WithUnretained.swift */, + 8E63F3142AB0D6370010A0CB /* Zip.swift */, + 8E63F3222AB0D6380010A0CB /* Zip+arity.swift */, + 8E63F3282AB0D6380010A0CB /* Zip+arity.tt */, + 8E63F3192AB0D6370010A0CB /* Zip+Collection.swift */, + ); + path = Observables; + sourceTree = ""; + }; + 8EFF11ED2AB0C09500399069 /* Disposables */ = { + isa = PBXGroup; + children = ( + 8EFF11EE2AB0C09500399069 /* DisposeBase.swift */, + 8EFF11EF2AB0C09500399069 /* DisposeBag.swift */, + 8EFF11F02AB0C09500399069 /* ScheduledDisposable.swift */, + 8EFF11F12AB0C09500399069 /* NopDisposable.swift */, + 8EFF11F22AB0C09500399069 /* SubscriptionDisposable.swift */, + 8EFF11F32AB0C09500399069 /* RefCountDisposable.swift */, + 8EFF11F42AB0C09500399069 /* CompositeDisposable.swift */, + 8EFF11F52AB0C09500399069 /* SingleAssignmentDisposable.swift */, + 8EFF11F62AB0C09500399069 /* SerialDisposable.swift */, + 8EFF11F72AB0C09500399069 /* BinaryDisposable.swift */, + 8EFF11F82AB0C09500399069 /* AnonymousDisposable.swift */, + 8EFF11F92AB0C09500399069 /* BooleanDisposable.swift */, + 8EFF11FA2AB0C09500399069 /* Disposables.swift */, + ); + path = Disposables; + sourceTree = ""; + }; + 8EFF12462AB0C09500399069 /* Concurrency */ = { + isa = PBXGroup; + children = ( + 8EFF12472AB0C09500399069 /* LockOwnerType.swift */, + 8EFF12482AB0C09500399069 /* SynchronizedDisposeType.swift */, + 8EFF12492AB0C09500399069 /* SynchronizedOnType.swift */, + 8EFF124A2AB0C09500399069 /* Lock.swift */, + 8EFF124B2AB0C09500399069 /* AsyncLock.swift */, + 8EFF124C2AB0C09500399069 /* SynchronizedUnsubscribeType.swift */, + ); + path = Concurrency; + sourceTree = ""; + }; + 8EFF12512AB0C09600399069 /* Extensions */ = { + isa = PBXGroup; + children = ( + 8EFF12522AB0C09600399069 /* Bag+Rx.swift */, + ); + path = Extensions; + sourceTree = ""; + }; + 8EFF12C32AB0C0A200399069 /* Observers */ = { + isa = PBXGroup; + children = ( + 8EFF12C42AB0C0A200399069 /* ObserverBase.swift */, + 8EFF12C52AB0C0A200399069 /* TailRecursiveSink.swift */, + 8EFF12C62AB0C0A200399069 /* AnonymousObserver.swift */, + ); + path = Observers; + sourceTree = ""; + }; + 8EFF12CB2AB0C0F200399069 /* Traits */ = { + isa = PBXGroup; + children = ( + 8EFF12CC2AB0C0F200399069 /* PrimitiveSequence */, + 8EFF12D62AB0C0F200399069 /* Infallible */, + ); + path = Traits; + sourceTree = ""; + }; + 8EFF12CC2AB0C0F200399069 /* PrimitiveSequence */ = { + isa = PBXGroup; + children = ( + 8EFF12CD2AB0C0F200399069 /* Completable+AndThen.swift */, + 8EFF12CE2AB0C0F200399069 /* PrimitiveSequence+Zip+arity.tt */, + 8EFF12CF2AB0C0F200399069 /* Completable.swift */, + 8EFF12D02AB0C0F200399069 /* Single.swift */, + 8EFF12D12AB0C0F200399069 /* PrimitiveSequence.swift */, + 8EFF12D22AB0C0F200399069 /* Maybe.swift */, + 8EFF12D32AB0C0F200399069 /* ObservableType+PrimitiveSequence.swift */, + 8EFF12D42AB0C0F200399069 /* PrimitiveSequence+Zip+arity.swift */, + 8EFF12D52AB0C0F200399069 /* PrimitiveSequence+Concurrency.swift */, + ); + path = PrimitiveSequence; + sourceTree = ""; + }; + 8EFF12D62AB0C0F200399069 /* Infallible */ = { + isa = PBXGroup; + children = ( + 8EFF12D72AB0C0F200399069 /* Infallible+Zip+arity.swift */, + 8EFF12D82AB0C0F200399069 /* Infallible+Concurrency.swift */, + 8EFF12D92AB0C0F200399069 /* Infallible+Zip+arity.tt */, + 8EFF12DA2AB0C0F200399069 /* Infallible+Create.swift */, + 8EFF12DB2AB0C0F200399069 /* Infallible+Operators.swift */, + 8EFF12DC2AB0C0F200399069 /* Infallible+Debug.swift */, + 8EFF12DD2AB0C0F200399069 /* Infallible+CombineLatest+arity.tt */, + 8EFF12DE2AB0C0F200399069 /* Infallible+CombineLatest+arity.swift */, + 8EFF12DF2AB0C0F200399069 /* Infallible.swift */, + 8EFF12E02AB0C0F200399069 /* Infallible+CombineLatest+Collection.swift */, + 8EFF12E12AB0C0F200399069 /* ObservableConvertibleType+Infallible.swift */, + ); + path = Infallible; + sourceTree = ""; + }; + 8EFF12F32AB0C0FF00399069 /* SwiftSupport */ = { + isa = PBXGroup; + children = ( + 8EFF12F42AB0C0FF00399069 /* SwiftSupport.swift */, + ); + path = SwiftSupport; + sourceTree = ""; + }; + 8EFF12F62AB0C10D00399069 /* Subjects */ = { + isa = PBXGroup; + children = ( + 8EFF12F72AB0C10D00399069 /* SubjectType.swift */, + 8EFF12F82AB0C10D00399069 /* BehaviorSubject.swift */, + 8EFF12F92AB0C10D00399069 /* AsyncSubject.swift */, + 8EFF12FA2AB0C10D00399069 /* ReplaySubject.swift */, + 8EFF12FB2AB0C10D00399069 /* PublishSubject.swift */, + ); + path = Subjects; + sourceTree = ""; + }; + 8EFF13012AB0C15500399069 /* Schedulers */ = { + isa = PBXGroup; + children = ( + 8EFF13022AB0C15500399069 /* RecursiveScheduler.swift */, + 8EFF13032AB0C15500399069 /* OperationQueueScheduler.swift */, + 8EFF13042AB0C15500399069 /* VirtualTimeScheduler.swift */, + 8EFF13052AB0C15500399069 /* SchedulerServices+Emulation.swift */, + 8EFF13062AB0C15500399069 /* CurrentThreadScheduler.swift */, + 8EFF13072AB0C15500399069 /* MainScheduler.swift */, + 8EFF13082AB0C15500399069 /* ConcurrentDispatchQueueScheduler.swift */, + 8EFF13092AB0C15500399069 /* Internal */, + 8EFF130F2AB0C15500399069 /* ConcurrentMainScheduler.swift */, + 8EFF13102AB0C15500399069 /* SerialDispatchQueueScheduler.swift */, + 8EFF13112AB0C15500399069 /* HistoricalScheduler.swift */, + 8EFF13122AB0C15500399069 /* VirtualTimeConverterType.swift */, + 8EFF13132AB0C15500399069 /* HistoricalSchedulerTimeConverter.swift */, + ); + path = Schedulers; + sourceTree = ""; + }; + 8EFF13092AB0C15500399069 /* Internal */ = { + isa = PBXGroup; + children = ( + 8EFF130A2AB0C15500399069 /* ScheduledItem.swift */, + 8EFF130B2AB0C15500399069 /* InvocableType.swift */, + 8EFF130C2AB0C15500399069 /* InvocableScheduledItem.swift */, + 8EFF130D2AB0C15500399069 /* DispatchQueueConfiguration.swift */, + 8EFF130E2AB0C15500399069 /* ScheduledItemType.swift */, + ); + path = Internal; + sourceTree = ""; + }; + A8F13C1C2316ADE700A70E91 = { + isa = PBXGroup; + children = ( + A8F13C312316AE3600A70E91 /* MultiPlatformBLEAdapter-Bridging-Header.h */, + A8F13C432316AF7600A70E91 /* RxBluetoothKit */, + A8F13C622316AF7600A70E91 /* RxSwift */, + A8F13C272316ADE700A70E91 /* classes */, + A8F13C262316ADE700A70E91 /* Products */, + ); + sourceTree = ""; + }; + A8F13C262316ADE700A70E91 /* Products */ = { + isa = PBXGroup; + children = ( + A8F13C252316ADE700A70E91 /* libMultiPlatformBLEAdapter.a */, + ); + name = Products; + sourceTree = ""; + }; + A8F13C272316ADE700A70E91 /* classes */ = { + isa = PBXGroup; + children = ( + A8F13E012316BE2F00A70E91 /* Utils */, + A8F13DF92316BDFB00A70E91 /* BleClientManager.h */, + A8F13DF62316BDFA00A70E91 /* BleError.swift */, + A8F13DF52316BDFA00A70E91 /* BleEvent.swift */, + A8F13DF82316BDFA00A70E91 /* BleExtensions.swift */, + A8F13DFA2316BDFB00A70E91 /* BleModule.swift */, + A8F13DF72316BDFA00A70E91 /* BleUtils.swift */, + A8F13C282316ADE700A70E91 /* MultiPlatformBLEAdapter.h */, + A8F13C292316ADE700A70E91 /* MultiPlatformBLEAdapter.m */, + 81B95B91234B256000D96D28 /* BleAdapter.swift */, + 816FE39A234F29B3008BF70D /* BleAdapterFactory.swift */, + ); + path = classes; + sourceTree = ""; + }; + A8F13C432316AF7600A70E91 /* RxBluetoothKit */ = { + isa = PBXGroup; + children = ( + 8EF49F482AB1CE400019E5F9 /* ManagerType.swift */, + 8EF49F3A2AB1CD3E0019E5F9 /* CBCentral+Uuid.swift */, + 8EF49F3C2AB1CD720019E5F9 /* CBCentralManagerDelegateWrapper.swift */, + 8EF49F402AB1CDDE0019E5F9 /* CBPeripheralDelegateWrapper.swift */, + 8EF49F382AB1CCF30019E5F9 /* Array+Utils.swift */, + A8F13C442316AF7600A70E91 /* RxCBCharacteristic.swift */, + A8F13C452316AF7600A70E91 /* RxCBService.swift */, + A8F13C462316AF7600A70E91 /* RxDescriptorType.swift */, + A8F13C472316AF7600A70E91 /* BluetoothState.swift */, + A8F13C482316AF7600A70E91 /* Peripheral.swift */, + A8F13C492316AF7600A70E91 /* Logging.swift */, + A8F13C4A2316AF7600A70E91 /* RxCharacteristicType.swift */, + A8F13C4B2316AF7600A70E91 /* DeviceIdentifiers.swift */, + A8F13C4C2316AF7600A70E91 /* Service.swift */, + A8F13C4D2316AF7600A70E91 /* RxServiceType.swift */, + A8F13C4E2316AF7600A70E91 /* BluetoothManager.swift */, + A8F13C4F2316AF7600A70E91 /* BluetoothError.swift */, + A8F13C502316AF7600A70E91 /* Peripheral+Convenience.swift */, + A8F13C512316AF7600A70E91 /* AdvertisementData.swift */, + A8F13C522316AF7600A70E91 /* RxBluetoothKit.h */, + A8F13C532316AF7600A70E91 /* RxCentralManagerType.swift */, + A8F13C542316AF7600A70E91 /* RxCBCentralManager.swift */, + A8F13C552316AF7600A70E91 /* RestoredState.swift */, + A8F13C562316AF7600A70E91 /* Descriptor.swift */, + A8F13C572316AF7600A70E91 /* Boxes.swift */, + A8F13C582316AF7600A70E91 /* RxCBDescriptor.swift */, + A8F13C592316AF7600A70E91 /* Observable+Absorb.swift */, + A8F13C5A2316AF7600A70E91 /* UUIDIdentifiable.swift */, + A8F13C5B2316AF7600A70E91 /* ScanOperation.swift */, + A8F13C5C2316AF7600A70E91 /* ScannedPeripheral.swift */, + A8F13C5D2316AF7600A70E91 /* Observable+QueueSubscribeOn.swift */, + A8F13C5E2316AF7600A70E91 /* Characteristic.swift */, + A8F13C5F2316AF7600A70E91 /* Unimplemented.swift */, + A8F13C602316AF7600A70E91 /* RxCBPeripheral.swift */, + A8F13C612316AF7600A70E91 /* RxPeripheralType.swift */, + ); + path = RxBluetoothKit; + sourceTree = ""; + }; + A8F13C622316AF7600A70E91 /* RxSwift */ = { + isa = PBXGroup; + children = ( + 8E63F2E22AB0D5D60010A0CB /* Observables */, + 8E63F2CE2AB0CE770010A0CB /* Platform */, + 8EFF133F2AB0C21F00399069 /* SchedulerType.swift */, + 8EFF133A2AB0C17800399069 /* Reactive.swift */, + 8EFF133B2AB0C17800399069 /* Rx.swift */, + 8EFF13392AB0C17800399069 /* RxMutableBox.swift */, + 8EFF13012AB0C15500399069 /* Schedulers */, + 8EFF12F62AB0C10D00399069 /* Subjects */, + 8EFF12F32AB0C0FF00399069 /* SwiftSupport */, + 8EFF12CB2AB0C0F200399069 /* Traits */, + 8EFF12C32AB0C0A200399069 /* Observers */, + 8EFF12C22AB0C0A200399069 /* ObserverType.swift */, + 8EFF12532AB0C09600399069 /* AnyObserver.swift */, + 8EFF12552AB0C09600399069 /* Binder.swift */, + 8EFF11EC2AB0C09500399069 /* Cancelable.swift */, + 8EFF12462AB0C09500399069 /* Concurrency */, + 8EFF12582AB0C09600399069 /* ConnectableObservableType.swift */, + 8EFF11EA2AB0C09500399069 /* Date+Dispatch.swift */, + 8EFF11E92AB0C09500399069 /* Disposable.swift */, + 8EFF11ED2AB0C09500399069 /* Disposables */, + 8EFF11FB2AB0C09500399069 /* Errors.swift */, + 8EFF11EB2AB0C09500399069 /* Event.swift */, + 8EFF12512AB0C09600399069 /* Extensions */, + 8EFF12562AB0C09600399069 /* GroupedObservable.swift */, + 8EFF124F2AB0C09500399069 /* ImmediateSchedulerType.swift */, + 8EFF124D2AB0C09500399069 /* Info.plist */, + 8EFF12542AB0C09600399069 /* Observable.swift */, + 8EFF124E2AB0C09500399069 /* Observable+Concurrency.swift */, + 8EFF12572AB0C09600399069 /* ObservableConvertibleType.swift */, + 8EFF12452AB0C09500399069 /* ObservableType.swift */, + 8EFF12502AB0C09500399069 /* ObservableType+Extensions.swift */, + ); + path = RxSwift; + sourceTree = ""; + }; + A8F13E012316BE2F00A70E91 /* Utils */ = { + isa = PBXGroup; + children = ( + A8F13E022316BE2F00A70E91 /* DisposableMap.swift */, + A8F13E032316BE2F00A70E91 /* SafePromise.swift */, + ); + path = Utils; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + A8F13C242316ADE700A70E91 /* MultiPlatformBLEAdapter */ = { + isa = PBXNativeTarget; + buildConfigurationList = A8F13C2E2316ADE700A70E91 /* Build configuration list for PBXNativeTarget "MultiPlatformBLEAdapter" */; + buildPhases = ( + A8F13C212316ADE700A70E91 /* Sources */, + A8F13C222316ADE700A70E91 /* Frameworks */, + A8F13C232316ADE700A70E91 /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = MultiPlatformBLEAdapter; + productName = MultiPlatformBLEAdapter; + productReference = A8F13C252316ADE700A70E91 /* libMultiPlatformBLEAdapter.a */; + productType = "com.apple.product-type.library.static"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + A8F13C1D2316ADE700A70E91 /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 1020; + ORGANIZATIONNAME = Polidea; + TargetAttributes = { + A8F13C242316ADE700A70E91 = { + CreatedOnToolsVersion = 10.2.1; + LastSwiftMigration = 1020; + }; + }; + }; + buildConfigurationList = A8F13C202316ADE700A70E91 /* Build configuration list for PBXProject "MultiPlatformBLEAdapter" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = A8F13C1C2316ADE700A70E91; + productRefGroup = A8F13C262316ADE700A70E91 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + A8F13C242316ADE700A70E91 /* MultiPlatformBLEAdapter */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + A8F13C212316ADE700A70E91 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8EFF12602AB0C09600399069 /* NopDisposable.swift in Sources */, + 8EFF12BB2AB0C09600399069 /* Bag+Rx.swift in Sources */, + 8E63F35D2AB0D6390010A0CB /* Skip.swift in Sources */, + 8EFF12FF2AB0C10D00399069 /* ReplaySubject.swift in Sources */, + 8E63F3382AB0D6390010A0CB /* Throttle.swift in Sources */, + 8EFF13162AB0C15500399069 /* VirtualTimeScheduler.swift in Sources */, + 8EFF133D2AB0C17800399069 /* Reactive.swift in Sources */, + 8EFF131E2AB0C15500399069 /* DispatchQueueConfiguration.swift in Sources */, + 8EFF12BA2AB0C09600399069 /* ObservableType+Extensions.swift in Sources */, + 8EFF131F2AB0C15500399069 /* ScheduledItemType.swift in Sources */, + A8F13D0A2316AF7600A70E91 /* BluetoothState.swift in Sources */, + 8EFF12642AB0C09600399069 /* SingleAssignmentDisposable.swift in Sources */, + A8F13D0B2316AF7600A70E91 /* Peripheral.swift in Sources */, + A8F13D182316AF7600A70E91 /* Descriptor.swift in Sources */, + 8E63F33C2AB0D6390010A0CB /* Enumerated.swift in Sources */, + A8F13D0F2316AF7600A70E91 /* Service.swift in Sources */, + A8F13D1E2316AF7600A70E91 /* ScannedPeripheral.swift in Sources */, + 8EFF126A2AB0C09600399069 /* Errors.swift in Sources */, + 8EFF12CA2AB0C0A200399069 /* AnonymousObserver.swift in Sources */, + 8EFF12B32AB0C09600399069 /* SynchronizedDisposeType.swift in Sources */, + 8EFF12EA2AB0C0F200399069 /* Infallible+Zip+arity.swift in Sources */, + 81B95B92234B256000D96D28 /* BleAdapter.swift in Sources */, + A8F13E042316BE2F00A70E91 /* DisposableMap.swift in Sources */, + 8E63F3612AB0D6390010A0CB /* ShareReplayScope.swift in Sources */, + 8EFF12BE2AB0C09600399069 /* Binder.swift in Sources */, + 8E63F35F2AB0D6390010A0CB /* CombineLatest.swift in Sources */, + 8E63F35B2AB0D6390010A0CB /* Zip.swift in Sources */, + 8EFF12EB2AB0C0F200399069 /* Infallible+Concurrency.swift in Sources */, + A8F13D142316AF7600A70E91 /* AdvertisementData.swift in Sources */, + 8E63F3592AB0D6390010A0CB /* Empty.swift in Sources */, + 8E63F3452AB0D6390010A0CB /* Timeout.swift in Sources */, + 8E63F3572AB0D6390010A0CB /* Take.swift in Sources */, + 8EFF12EF2AB0C0F200399069 /* Infallible+CombineLatest+arity.swift in Sources */, + 8EFF12B12AB0C09600399069 /* ObservableType.swift in Sources */, + 8EFF12E32AB0C0F200399069 /* Completable.swift in Sources */, + 8E63F3332AB0D6390010A0CB /* Scan.swift in Sources */, + 8EFF13142AB0C15500399069 /* RecursiveScheduler.swift in Sources */, + 8EFF12662AB0C09600399069 /* BinaryDisposable.swift in Sources */, + 8E63F3642AB0D6390010A0CB /* Optional.swift in Sources */, + 8E63F3692AB0D6390010A0CB /* Zip+arity.swift in Sources */, + 8E63F3582AB0D6390010A0CB /* Merge.swift in Sources */, + 8E63F3422AB0D6390010A0CB /* ElementAt.swift in Sources */, + 8E63F3352AB0D6390010A0CB /* Concat.swift in Sources */, + 8EFF12EC2AB0C0F200399069 /* Infallible+Create.swift in Sources */, + A8F13DFF2316BDFB00A70E91 /* BleModule.swift in Sources */, + 8E63F3462AB0D6390010A0CB /* AddRef.swift in Sources */, + 8EF49F412AB1CDDE0019E5F9 /* CBPeripheralDelegateWrapper.swift in Sources */, + 8E63F32C2AB0D6390010A0CB /* Never.swift in Sources */, + 8EFF12E92AB0C0F200399069 /* PrimitiveSequence+Concurrency.swift in Sources */, + 8EFF12B72AB0C09600399069 /* SynchronizedUnsubscribeType.swift in Sources */, + 8EFF13222AB0C15500399069 /* HistoricalScheduler.swift in Sources */, + 8E63F3362AB0D6390010A0CB /* Do.swift in Sources */, + 8EFF125F2AB0C09600399069 /* ScheduledDisposable.swift in Sources */, + A8F13D162316AF7600A70E91 /* RxCBCentralManager.swift in Sources */, + 8EFF131C2AB0C15500399069 /* InvocableType.swift in Sources */, + A8F13D212316AF7600A70E91 /* Unimplemented.swift in Sources */, + 8EFF12682AB0C09600399069 /* BooleanDisposable.swift in Sources */, + 8E63F32E2AB0D6390010A0CB /* Switch.swift in Sources */, + 8E63F3392AB0D6390010A0CB /* WithLatestFrom.swift in Sources */, + 8E63F3322AB0D6390010A0CB /* StartWith.swift in Sources */, + 8E63F35E2AB0D6390010A0CB /* TakeLast.swift in Sources */, + 8E63F32B2AB0D6390010A0CB /* DefaultIfEmpty.swift in Sources */, + 8E63F3432AB0D6390010A0CB /* Filter.swift in Sources */, + A8F13DFC2316BDFB00A70E91 /* BleError.swift in Sources */, + A8F13D0E2316AF7600A70E91 /* DeviceIdentifiers.swift in Sources */, + 8E63F3622AB0D6390010A0CB /* Sink.swift in Sources */, + 8E63F3542AB0D6390010A0CB /* Debug.swift in Sources */, + 8EFF12F22AB0C0F200399069 /* ObservableConvertibleType+Infallible.swift in Sources */, + 8EFF12632AB0C09600399069 /* CompositeDisposable.swift in Sources */, + 8E63F3602AB0D6390010A0CB /* Zip+Collection.swift in Sources */, + A8F13D0D2316AF7600A70E91 /* RxCharacteristicType.swift in Sources */, + 8E63F33D2AB0D6390010A0CB /* Buffer.swift in Sources */, + 8EFF13402AB0C21F00399069 /* SchedulerType.swift in Sources */, + 8EFF12BF2AB0C09600399069 /* GroupedObservable.swift in Sources */, + 8E63F34B2AB0D6390010A0CB /* CompactMap.swift in Sources */, + 8E63F36F2AB0D6390010A0CB /* AsMaybe.swift in Sources */, + 8E63F33B2AB0D6390010A0CB /* Deferred.swift in Sources */, + 8EFF12E52AB0C0F200399069 /* PrimitiveSequence.swift in Sources */, + 8E63F3672AB0D6390010A0CB /* Just.swift in Sources */, + 8EFF125D2AB0C09600399069 /* DisposeBase.swift in Sources */, + 8E63F3522AB0D6390010A0CB /* Materialize.swift in Sources */, + 8E63F2DF2AB0CFB10010A0CB /* PriorityQueue.swift in Sources */, + 8E63F2D72AB0CF1E0010A0CB /* Platform.Linux.swift in Sources */, + 8EFF133C2AB0C17800399069 /* RxMutableBox.swift in Sources */, + 8EFF12FE2AB0C10D00399069 /* AsyncSubject.swift in Sources */, + 8E63F3402AB0D6390010A0CB /* SkipWhile.swift in Sources */, + A8F13E052316BE2F00A70E91 /* SafePromise.swift in Sources */, + 8E63F3482AB0D6390010A0CB /* CombineLatest+Collection.swift in Sources */, + 8EF49F492AB1CE400019E5F9 /* ManagerType.swift in Sources */, + 8EFF12612AB0C09600399069 /* SubscriptionDisposable.swift in Sources */, + 8E63F36D2AB0D6390010A0CB /* SkipUntil.swift in Sources */, + 8E63F2D92AB0CF400010A0CB /* RecursiveLock.swift in Sources */, + 8E63F3552AB0D6390010A0CB /* Create.swift in Sources */, + A8F13D092316AF7600A70E91 /* RxDescriptorType.swift in Sources */, + 8EFF13182AB0C15500399069 /* CurrentThreadScheduler.swift in Sources */, + 8EFF125C2AB0C09600399069 /* Cancelable.swift in Sources */, + A8F13D112316AF7600A70E91 /* BluetoothManager.swift in Sources */, + 8EFF13172AB0C15500399069 /* SchedulerServices+Emulation.swift in Sources */, + 8EFF12C92AB0C0A200399069 /* TailRecursiveSink.swift in Sources */, + 8EFF125A2AB0C09600399069 /* Date+Dispatch.swift in Sources */, + 8E63F2DD2AB0CF830010A0CB /* InfiniteSequence.swift in Sources */, + 8E63F3702AB0D6390010A0CB /* ToArray.swift in Sources */, + 8EFF12E62AB0C0F200399069 /* Maybe.swift in Sources */, + 8EFF12592AB0C09600399069 /* Disposable.swift in Sources */, + 8E63F34E2AB0D6390010A0CB /* First.swift in Sources */, + 8E63F35C2AB0D6390010A0CB /* CombineLatest+arity.swift in Sources */, + 8E63F34F2AB0D6390010A0CB /* Amb.swift in Sources */, + A8F13D1B2316AF7600A70E91 /* Observable+Absorb.swift in Sources */, + 8EFF12652AB0C09600399069 /* SerialDisposable.swift in Sources */, + 8E63F34D2AB0D6390010A0CB /* DistinctUntilChanged.swift in Sources */, + 8E63F2E12AB0CFC30010A0CB /* Queue.swift in Sources */, + 8E63F33A2AB0D6390010A0CB /* Debounce.swift in Sources */, + 8E63F3412AB0D6390010A0CB /* ObserveOn.swift in Sources */, + A8F13D1A2316AF7600A70E91 /* RxCBDescriptor.swift in Sources */, + 8EFF12B82AB0C09600399069 /* Observable+Concurrency.swift in Sources */, + 8EFF12C82AB0C0A200399069 /* ObserverBase.swift in Sources */, + 8EFF13202AB0C15500399069 /* ConcurrentMainScheduler.swift in Sources */, + 8EF49F392AB1CCF30019E5F9 /* Array+Utils.swift in Sources */, + 8EFF13242AB0C15500399069 /* HistoricalSchedulerTimeConverter.swift in Sources */, + A8F13D072316AF7600A70E91 /* RxCBCharacteristic.swift in Sources */, + 8EFF13002AB0C10D00399069 /* PublishSubject.swift in Sources */, + A8F13D122316AF7600A70E91 /* BluetoothError.swift in Sources */, + 8EFF12C12AB0C09600399069 /* ConnectableObservableType.swift in Sources */, + 8EF49F3B2AB1CD3E0019E5F9 /* CBCentral+Uuid.swift in Sources */, + 8E63F3472AB0D6390010A0CB /* AsSingle.swift in Sources */, + 8EFF12F02AB0C0F200399069 /* Infallible.swift in Sources */, + 8E63F34A2AB0D6390010A0CB /* Window.swift in Sources */, + 8E63F3632AB0D6390010A0CB /* Delay.swift in Sources */, + A8F13D232316AF7600A70E91 /* RxPeripheralType.swift in Sources */, + 8EFF133E2AB0C17800399069 /* Rx.swift in Sources */, + A8F13D0C2316AF7600A70E91 /* Logging.swift in Sources */, + 8E63F32D2AB0D6390010A0CB /* GroupBy.swift in Sources */, + 8E63F3502AB0D6390010A0CB /* Error.swift in Sources */, + 8EFF12B92AB0C09600399069 /* ImmediateSchedulerType.swift in Sources */, + A8F13D152316AF7600A70E91 /* RxCentralManagerType.swift in Sources */, + 8EF49F3D2AB1CD720019E5F9 /* CBCentralManagerDelegateWrapper.swift in Sources */, + 8EFF12F52AB0C0FF00399069 /* SwiftSupport.swift in Sources */, + 8EFF12B52AB0C09600399069 /* Lock.swift in Sources */, + 8EFF12ED2AB0C0F200399069 /* Infallible+Operators.swift in Sources */, + A8F13D132316AF7600A70E91 /* Peripheral+Convenience.swift in Sources */, + 8E63F3372AB0D6390010A0CB /* SwitchIfEmpty.swift in Sources */, + 8EFF13212AB0C15500399069 /* SerialDispatchQueueScheduler.swift in Sources */, + A8F13D222316AF7600A70E91 /* RxCBPeripheral.swift in Sources */, + 8EFF131A2AB0C15500399069 /* ConcurrentDispatchQueueScheduler.swift in Sources */, + 8EFF12B42AB0C09600399069 /* SynchronizedOnType.swift in Sources */, + 8EFF131D2AB0C15500399069 /* InvocableScheduledItem.swift in Sources */, + 8EFF12C02AB0C09600399069 /* ObservableConvertibleType.swift in Sources */, + 8E63F3312AB0D6390010A0CB /* RetryWhen.swift in Sources */, + A8F13D1D2316AF7600A70E91 /* ScanOperation.swift in Sources */, + 8E63F3302AB0D6390010A0CB /* Producer.swift in Sources */, + 8EFF13192AB0C15500399069 /* MainScheduler.swift in Sources */, + 8E63F2D32AB0CEEC0010A0CB /* DispatchQueue+Extensions.swift in Sources */, + 8E63F3532AB0D6390010A0CB /* SubscribeOn.swift in Sources */, + 8E63F36A2AB0D6390010A0CB /* Map.swift in Sources */, + 8E63F34C2AB0D6390010A0CB /* DelaySubscription.swift in Sources */, + 8EFF12C72AB0C0A200399069 /* ObserverType.swift in Sources */, + 8E63F36B2AB0D6390010A0CB /* TakeWithPredicate.swift in Sources */, + 8E63F3492AB0D6390010A0CB /* Decode.swift in Sources */, + 8E63F2D52AB0CF050010A0CB /* Platform.Darwin.swift in Sources */, + 8EFF12E42AB0C0F200399069 /* Single.swift in Sources */, + A8F13D1C2316AF7600A70E91 /* UUIDIdentifiable.swift in Sources */, + A8F13D102316AF7600A70E91 /* RxServiceType.swift in Sources */, + A8F13DFB2316BDFB00A70E91 /* BleEvent.swift in Sources */, + 8EFF12BC2AB0C09600399069 /* AnyObserver.swift in Sources */, + 8E63F2D12AB0CE9B0010A0CB /* AtomicInt.swift in Sources */, + A8F13D202316AF7600A70E91 /* Characteristic.swift in Sources */, + A8F13D082316AF7600A70E91 /* RxCBService.swift in Sources */, + 8E63F3662AB0D6390010A0CB /* Catch.swift in Sources */, + 8E63F3652AB0D6390010A0CB /* Reduce.swift in Sources */, + 8EFF12FD2AB0C10D00399069 /* BehaviorSubject.swift in Sources */, + 8EFF12E82AB0C0F200399069 /* PrimitiveSequence+Zip+arity.swift in Sources */, + A8F13DFE2316BDFB00A70E91 /* BleExtensions.swift in Sources */, + 8E63F3562AB0D6390010A0CB /* Sample.swift in Sources */, + 8EFF12B62AB0C09600399069 /* AsyncLock.swift in Sources */, + 8E63F3512AB0D6390010A0CB /* Generate.swift in Sources */, + 816FE39B234F29B3008BF70D /* BleAdapterFactory.swift in Sources */, + 8EFF125E2AB0C09600399069 /* DisposeBag.swift in Sources */, + A8F13D1F2316AF7600A70E91 /* Observable+QueueSubscribeOn.swift in Sources */, + A8F13D192316AF7600A70E91 /* Boxes.swift in Sources */, + 8E63F33F2AB0D6390010A0CB /* Sequence.swift in Sources */, + A8F13C2A2316ADE700A70E91 /* MultiPlatformBLEAdapter.m in Sources */, + 8EFF12FC2AB0C10D00399069 /* SubjectType.swift in Sources */, + 8EFF12672AB0C09600399069 /* AnonymousDisposable.swift in Sources */, + 8EFF12E22AB0C0F200399069 /* Completable+AndThen.swift in Sources */, + 8EFF12622AB0C09600399069 /* RefCountDisposable.swift in Sources */, + 8E63F3342AB0D6390010A0CB /* Using.swift in Sources */, + 8E63F36C2AB0D6390010A0CB /* Timer.swift in Sources */, + 8E63F2DB2AB0CF730010A0CB /* Bag.swift in Sources */, + A8F13D172316AF7600A70E91 /* RestoredState.swift in Sources */, + 8EFF131B2AB0C15500399069 /* ScheduledItem.swift in Sources */, + 8EFF12692AB0C09600399069 /* Disposables.swift in Sources */, + 8EFF12E72AB0C0F200399069 /* ObservableType+PrimitiveSequence.swift in Sources */, + 8EFF125B2AB0C09600399069 /* Event.swift in Sources */, + 8EFF12BD2AB0C09600399069 /* Observable.swift in Sources */, + 8EFF12EE2AB0C0F200399069 /* Infallible+Debug.swift in Sources */, + 8E63F3682AB0D6390010A0CB /* Repeat.swift in Sources */, + 8E63F3442AB0D6390010A0CB /* SingleAsync.swift in Sources */, + 8E63F32F2AB0D6390010A0CB /* WithUnretained.swift in Sources */, + 8EFF12B22AB0C09600399069 /* LockOwnerType.swift in Sources */, + 8EFF13152AB0C15500399069 /* OperationQueueScheduler.swift in Sources */, + 8E63F35A2AB0D6390010A0CB /* Dematerialize.swift in Sources */, + 8E63F33E2AB0D6390010A0CB /* Range.swift in Sources */, + 8EFF13232AB0C15500399069 /* VirtualTimeConverterType.swift in Sources */, + A8F13DFD2316BDFB00A70E91 /* BleUtils.swift in Sources */, + 8EFF12F12AB0C0F200399069 /* Infallible+CombineLatest+Collection.swift in Sources */, + 8E63F36E2AB0D6390010A0CB /* Multicast.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + A8F13C2C2316ADE700A70E91 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_VERSION = 4.2; + }; + name = Debug; + }; + A8F13C2D2316ADE700A70E91 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_VERSION = 4.2; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + A8F13C2F2316ADE700A70E91 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = WR35VQMY5K; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + OTHER_LDFLAGS = "-ObjC"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_OBJC_BRIDGING_HEADER = "MultiPlatformBLEAdapter-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + A8F13C302316ADE700A70E91 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = WR35VQMY5K; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + OTHER_LDFLAGS = "-ObjC"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_OBJC_BRIDGING_HEADER = "MultiPlatformBLEAdapter-Bridging-Header.h"; + SWIFT_VERSION = 4.2; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + A8F13C202316ADE700A70E91 /* Build configuration list for PBXProject "MultiPlatformBLEAdapter" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A8F13C2C2316ADE700A70E91 /* Debug */, + A8F13C2D2316ADE700A70E91 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A8F13C2E2316ADE700A70E91 /* Build configuration list for PBXNativeTarget "MultiPlatformBLEAdapter" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A8F13C2F2316ADE700A70E91 /* Debug */, + A8F13C302316ADE700A70E91 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = A8F13C1D2316ADE700A70E91 /* Project object */; +} diff --git a/ios/MultiPlatformBleAdapter/iOS/MultiPlatformBLEAdapter.xcodeproj/xcshareddata/xcschemes/MultiPlatformBLEAdapter.xcscheme b/ios/MultiPlatformBleAdapter/iOS/MultiPlatformBLEAdapter.xcodeproj/xcshareddata/xcschemes/MultiPlatformBLEAdapter.xcscheme new file mode 100644 index 000000000..b198055c9 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/MultiPlatformBLEAdapter.xcodeproj/xcshareddata/xcschemes/MultiPlatformBLEAdapter.xcscheme @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/AdvertisementData.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/AdvertisementData.swift new file mode 100644 index 000000000..85427356a --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/AdvertisementData.swift @@ -0,0 +1,62 @@ +import Foundation +import CoreBluetooth + +/// Convenience class which helps reading advertisement data +public struct AdvertisementData { + /// Advertisement data dictionary that contains all information advertised by peripheral. + public let advertisementData: [String: Any] + + /// Creates advertisement data based on CoreBluetooth's dictionary + /// - parameter advertisementData: Core Bluetooth's advertisement data + public init(advertisementData: [String: Any]) { + self.advertisementData = advertisementData + } + + /// A string containing the local name of a peripheral. + public var localName: String? { + return advertisementData[CBAdvertisementDataLocalNameKey] as? String + } + + /// A Data object containing the manufacturer data of a peripheral. + public var manufacturerData: Data? { + return advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data + } + + /// A dictionary containing service-specific advertisement data. + /// The keys are CBUUID objects, representing CBService UUIDs. The values are Data objects, + /// representing service-specific data. + public var serviceData: [CBUUID: Data]? { + return advertisementData[CBAdvertisementDataServiceDataKey] as? [CBUUID: Data] + } + + /// An array of service UUIDs. + public var serviceUUIDs: [CBUUID]? { + return advertisementData[CBAdvertisementDataServiceUUIDsKey] as? [CBUUID] + } + + /// An array of one or more CBUUID objects, representing CBService UUIDs that were found in the “overflow” + /// area of the advertisement data. + public var overflowServiceUUIDs: [CBUUID]? { + return advertisementData[CBAdvertisementDataOverflowServiceUUIDsKey] as? [CBUUID] + } + + /// A number (an instance of NSNumber) containing the transmit power of a peripheral. + /// This key and value are available if the broadcaster (peripheral) + /// provides its Tx power level in its advertising packet. + /// Using the RSSI value and the Tx power level, it is possible to calculate path loss. + public var txPowerLevel: NSNumber? { + return advertisementData[CBAdvertisementDataTxPowerLevelKey] as? NSNumber + } + + /// A Boolean value that indicates whether the advertising event type is connectable. + /// The value for this key is an NSNumber object. You can use this value to determine whether + /// a peripheral is connectable at a particular moment. + public var isConnectable: Bool? { + return advertisementData[CBAdvertisementDataIsConnectable] as? Bool + } + + /// An array of one or more CBUUID objects, representing CBService UUIDs. + public var solicitedServiceUUIDs: [CBUUID]? { + return advertisementData[CBAdvertisementDataSolicitedServiceUUIDsKey] as? [CBUUID] + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Array+Utils.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Array+Utils.swift new file mode 100644 index 000000000..c2d864ba1 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Array+Utils.swift @@ -0,0 +1,11 @@ +import Foundation + +extension Array where Element: Equatable { + @discardableResult mutating func remove(object: Element) -> Bool { + if let index = firstIndex(of: object) { + self.remove(at: index) + return true + } + return false + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/BluetoothError.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/BluetoothError.swift new file mode 100644 index 000000000..d18e52684 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/BluetoothError.swift @@ -0,0 +1,195 @@ +import Foundation +import CoreBluetooth + +/// Bluetooth error which can be emitted by RxBluetoothKit created observables. +public enum BluetoothError: Error { + /// Emitted when the object that is the source of Observable was destroyed and event was emitted nevertheless. + /// To mitigate it dispose all of your subscriptions before deinitializing + /// object that created Observables that subscriptions are made to. + case destroyed + // Emitted when `CentralManager.scanForPeripherals` called and there is already ongoing scan + case scanInProgress + // Emitted when `PeripheralManager.startAdvertising` called and there is already ongoing advertisement + case advertisingInProgress + case advertisingStartFailed(Error) + // States + case bluetoothUnsupported + case bluetoothUnauthorized + case bluetoothPoweredOff + case bluetoothInUnknownState + case bluetoothResetting + // Peripheral + case peripheralIsAlreadyObservingConnection(Peripheral) + @available(*, deprecated, renamed: "BluetoothError.peripheralIsAlreadyObservingConnection") + case peripheralIsConnectingOrAlreadyConnected(Peripheral) + case peripheralConnectionFailed(Peripheral, Error?) + case peripheralDisconnected(Peripheral, Error?) + case peripheralRSSIReadFailed(Peripheral, Error?) + // Services + case servicesDiscoveryFailed(Peripheral, Error?) + case includedServicesDiscoveryFailed(Peripheral, Error?) + case addingServiceFailed(CBService, Error?) + // Characteristics + case characteristicsDiscoveryFailed(Service, Error?) + case characteristicWriteFailed(Characteristic, Error?) + case characteristicReadFailed(Characteristic, Error?) + case characteristicNotifyChangeFailed(Characteristic, Error?) + case characteristicSetNotifyValueFailed(Characteristic, Error?) + // Descriptors + case descriptorsDiscoveryFailed(Characteristic, Error?) + case descriptorWriteFailed(Descriptor, Error?) + case descriptorReadFailed(Descriptor, Error?) + // L2CAP + case openingL2CAPChannelFailed(Peripheral, Error?) + case publishingL2CAPChannelFailed(CBL2CAPPSM, Error?) + // Unknown + case unknownWriteType +} + +extension BluetoothError: CustomStringConvertible { + + /// Human readable description of bluetooth error + public var description: String { + switch self { + case .destroyed: + return """ + The object that is the source of this Observable was destroyed. + It's programmer's error, please check documentation of error for more details + """ + case .scanInProgress: + return """ + Tried to scan for peripheral when there is already ongoing scan. + You can have only 1 ongoing scanning, please check documentation of CentralManager for more details + """ + case .advertisingInProgress: + return """ + Tried to advertise when there is already advertising ongoing. + You can have only 1 ongoing advertising, please check documentation of PeripheralManager for more details + """ + case let .advertisingStartFailed(err): + return "Start advertising error occured: \(err.localizedDescription)" + case .bluetoothUnsupported: + return "Bluetooth is unsupported" + case .bluetoothUnauthorized: + return "Bluetooth is unauthorized" + case .bluetoothPoweredOff: + return "Bluetooth is powered off" + case .bluetoothInUnknownState: + return "Bluetooth is in unknown state" + case .bluetoothResetting: + return "Bluetooth is resetting" + // Peripheral + case .peripheralIsAlreadyObservingConnection, .peripheralIsConnectingOrAlreadyConnected: + return """ + Peripheral connection is already being observed. + You cannot try to establishConnection to peripheral when you have ongoing + connection (previously establishConnection subscription was not disposed). + """ + case let .peripheralConnectionFailed(_, err): + return "Connection error has occured: \(err?.localizedDescription ?? "-")" + case let .peripheralDisconnected(_, err): + return "Connection error has occured: \(err?.localizedDescription ?? "-")" + case let .peripheralRSSIReadFailed(_, err): + return "RSSI read failed : \(err?.localizedDescription ?? "-")" + // Services + case let .servicesDiscoveryFailed(_, err): + return "Services discovery error has occured: \(err?.localizedDescription ?? "-")" + case let .includedServicesDiscoveryFailed(_, err): + return "Included services discovery error has occured: \(err?.localizedDescription ?? "-")" + case let .addingServiceFailed(_, err): + return "Adding PeripheralManager service error has occured: \(err?.localizedDescription ?? "-")" + // Characteristics + case let .characteristicsDiscoveryFailed(_, err): + return "Characteristics discovery error has occured: \(err?.localizedDescription ?? "-")" + case let .characteristicWriteFailed(_, err): + return "Characteristic write error has occured: \(err?.localizedDescription ?? "-")" + case let .characteristicReadFailed(_, err): + return "Characteristic read error has occured: \(err?.localizedDescription ?? "-")" + case let .characteristicNotifyChangeFailed(_, err): + return "Characteristic notify change error has occured: \(err?.localizedDescription ?? "-")" + case let .characteristicSetNotifyValueFailed(_, err): + return "Characteristic isNotyfing value change error has occured: \(err?.localizedDescription ?? "-")" + // Descriptors + case let .descriptorsDiscoveryFailed(_, err): + return "Descriptor discovery error has occured: \(err?.localizedDescription ?? "-")" + case let .descriptorWriteFailed(_, err): + return "Descriptor write error has occured: \(err?.localizedDescription ?? "-")" + case let .descriptorReadFailed(_, err): + return "Descriptor read error has occured: \(err?.localizedDescription ?? "-")" + case let .openingL2CAPChannelFailed(_, err): + return "Opening L2CAP channel error has occured: \(err?.localizedDescription ?? "-")" + case let .publishingL2CAPChannelFailed(_, err): + return "Publishing L2CAP channel error has occured: \(err?.localizedDescription ?? "-")" + // Unknown + case .unknownWriteType: + return "Unknown write type" + } + } +} + +extension BluetoothError { + init?(state: BluetoothState) { + switch state { + case .unsupported: + self = .bluetoothUnsupported + case .unauthorized: + self = .bluetoothUnauthorized + case .poweredOff: + self = .bluetoothPoweredOff + case .unknown: + self = .bluetoothInUnknownState + case .resetting: + self = .bluetoothResetting + default: + return nil + } + } +} + +extension BluetoothError: Equatable {} + +// swiftlint:disable cyclomatic_complexity + +public func == (lhs: BluetoothError, rhs: BluetoothError) -> Bool { + switch (lhs, rhs) { + case (.scanInProgress, .scanInProgress): return true + case (.advertisingInProgress, .advertisingInProgress): return true + case (.advertisingStartFailed, .advertisingStartFailed): return true + // States + case (.bluetoothUnsupported, .bluetoothUnsupported): return true + case (.bluetoothUnauthorized, .bluetoothUnauthorized): return true + case (.bluetoothPoweredOff, .bluetoothPoweredOff): return true + case (.bluetoothInUnknownState, .bluetoothInUnknownState): return true + case (.bluetoothResetting, .bluetoothResetting): return true + // Services + case let (.servicesDiscoveryFailed(l, _), .servicesDiscoveryFailed(r, _)): return l == r + case let (.includedServicesDiscoveryFailed(l, _), .includedServicesDiscoveryFailed(r, _)): return l == r + case let (.addingServiceFailed(l, _), .addingServiceFailed(r, _)): return l == r + // Peripherals + case let (.peripheralIsAlreadyObservingConnection(l), .peripheralIsAlreadyObservingConnection(r)): return l == r + case let (.peripheralIsConnectingOrAlreadyConnected(l), .peripheralIsConnectingOrAlreadyConnected(r)): return l == r + case let (.peripheralIsAlreadyObservingConnection(l), .peripheralIsConnectingOrAlreadyConnected(r)): return l == r + case let (.peripheralIsConnectingOrAlreadyConnected(l), .peripheralIsAlreadyObservingConnection(r)): return l == r + case let (.peripheralConnectionFailed(l, _), .peripheralConnectionFailed(r, _)): return l == r + case let (.peripheralDisconnected(l, _), .peripheralDisconnected(r, _)): return l == r + case let (.peripheralRSSIReadFailed(l, _), .peripheralRSSIReadFailed(r, _)): return l == r + // Characteristics + case let (.characteristicsDiscoveryFailed(l, _), .characteristicsDiscoveryFailed(r, _)): return l == r + case let (.characteristicWriteFailed(l, _), .characteristicWriteFailed(r, _)): return l == r + case let (.characteristicReadFailed(l, _), .characteristicReadFailed(r, _)): return l == r + case let (.characteristicNotifyChangeFailed(l, _), .characteristicNotifyChangeFailed(r, _)): return l == r + case let (.characteristicSetNotifyValueFailed(l, _), .characteristicSetNotifyValueFailed(r, _)): return l == r + // Descriptors + case let (.descriptorsDiscoveryFailed(l, _), .descriptorsDiscoveryFailed(r, _)): return l == r + case let (.descriptorWriteFailed(l, _), .descriptorWriteFailed(r, _)): return l == r + case let (.descriptorReadFailed(l, _), .descriptorReadFailed(r, _)): return l == r + // L2CAP + case let (.openingL2CAPChannelFailed(l, _), .openingL2CAPChannelFailed(r, _)): return l == r + case let (.publishingL2CAPChannelFailed(l, _), .publishingL2CAPChannelFailed(r, _)): return l == r + // Unknown + case (.unknownWriteType, .unknownWriteType): return true + default: return false + } +} + +// swiftlint:enable cyclomatic_complexity diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/BluetoothManager.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/BluetoothManager.swift new file mode 100644 index 000000000..752199102 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/BluetoothManager.swift @@ -0,0 +1,357 @@ +import Foundation +import CoreBluetooth + +// swiftlint:disable line_length + +/// BluetoothManager is a class implementing ReactiveX API which wraps all Core Bluetooth Manager's functions allowing to +/// discover, connect to remote peripheral devices and more. It's using thin layer behind `RxCentralManagerType` protocol which is +/// implemented by `RxCBCentralManager` and should not be used directly by the user of a RxBluetoothKit library. +/// You can start using this class by discovering available services of nearby peripherals. Before calling any +/// public `BluetoothManager`'s functions you should make sure that Bluetooth is turned on and powered on. It can be done +/// by calling and observing returned value of `monitorState()` and then chaining it with `scanForPeripherals(_:options:)`: +/// ``` +/// bluetoothManager.rx_state +/// .filter { $0 == .PoweredOn } +/// .take(1) +/// .flatMap { manager.scanForPeripherals(nil) } +/// ``` +/// As a result you will receive `ScannedPeripheral` which contains `Peripheral` object, `AdvertisementData` and +/// peripheral's RSSI registered during discovery. You can then `connectToPeripheral(_:options:)` and do other operations. +/// - seealso: `Peripheral` +public class BluetoothManager { + + /// Implementation of Central Manager + private let centralManager: RxCentralManagerType + + /// Queue on which all observables are serialised if needed + private let subscriptionQueue = SerializedSubscriptionQueue() + + /// Lock which should be used before accessing any internal structures + private let lock = NSLock() + + /// Queue of scan operations which are waiting for an execution + private var scanQueue: [ScanOperation] = [] + + /// Unique identifier of an object. Should be removed in 4.0 + @available(*, deprecated) + public var objectId: UInt { + return centralManager.objectId + } + + public var manager: CBCentralManager { + return centralManager.centralManager + } + + // MARK: Initialization + + /// Creates new `BluetoothManager` instance with specified implementation of `RxCentralManagerType` protocol which will be + /// used by this class. Most of a time `RxCBCentralManager` should be chosen by the user. + /// - parameter centralManager: Implementation of `RxCentralManagerType` protocol used by this class. + init(centralManager: RxCentralManagerType) { + self.centralManager = centralManager + } + + /// Creates new `BluetoothManager` instance. By default all operations and events are executed and received on main thread. + /// - warning: If you pass background queue to the method make sure to observe results on main thread for UI related code. + /// - parameter queue: Queue on which bluetooth callbacks are received. By default main thread is used. + /// - parameter options: An optional dictionary containing initialization options for a central manager. + /// For more info about it please refer to [Central Manager initialization options](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCentralManager_Class/index.html) + public convenience init(queue: DispatchQueue = .main, + options: [String: AnyObject]? = nil) { + self.init(centralManager: RxCBCentralManager(queue: queue, options: options)) + } + + // MARK: Scanning + + /// Scans for `Peripheral`s after subscription to returned observable. First parameter `serviceUUIDs` is + /// an array of `Service` UUIDs which needs to be implemented by a peripheral to be discovered. If user don't want to + /// filter any peripherals, `nil` can be used instead. Additionally dictionary of + /// [CBCentralManager specific options](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCentralManager_Class/#//apple_ref/doc/constant_group/Peripheral_Scanning_Options) + /// can be passed to allow further customisation. + /// Scans by default are infinite streams of `ScannedPeripheral` structures which need to be stopped by the user. For + /// example this can be done by limiting scanning to certain number of peripherals or time: + /// ``` + /// bluetoothManager.scanForPeripherals(withServices: nil) + /// .timeout(3.0, timeoutScheduler) + /// .take(2) + /// ``` + /// + /// If different scan is currently in progress and peripherals needed by a user can be discovered by it, new scan is + /// shared. Otherwise scan is queued and will be executed when other scans finished with complete/error event or + /// were unsubscribed. As a result you will receive `ScannedPeripheral` which contains `Peripheral` object, + /// `AdvertisementData` and peripheral's RSSI registered during discovery. You can then + /// `connectToPeripheral(_:options:)` and do other operations. + /// - seealso: `Peripheral` + /// + /// - parameter serviceUUIDs: Services of peripherals to search for. Nil value will accept all peripherals. + /// - parameter options: Optional scanning options. + /// - returns: Infinite stream of scanned peripherals. + public func scanForPeripherals(withServices serviceUUIDs: [CBUUID]?, options: [String: Any]? = nil) + -> Observable { + return .deferred { [weak self] in + guard let strongSelf = self else { throw BluetoothError.destroyed } + let observable: Observable = { [weak self] () -> Observable in + guard let strongSelf = self else { return .error(BluetoothError.destroyed) } + // If it's possible use existing scan - take if from the queue + strongSelf.lock.lock(); defer { strongSelf.lock.unlock() } + if let elem = strongSelf.scanQueue.first(where: { $0.shouldAccept(serviceUUIDs) }) { + guard let serviceUUIDs = serviceUUIDs else { + return elem.observable + } + + // When binding to existing scan we need to make sure that services are + // filtered properly + return elem.observable.filter { scannedPeripheral in + if let services = scannedPeripheral.advertisementData.serviceUUIDs { + return Set(services).isSuperset(of: Set(serviceUUIDs)) + } + return false + } + } + + let scanOperationBox = WeakBox() + + // Create new scan which will be processed in a queue + let operation = Observable.create { [weak self] (element: AnyObserver) -> Disposable in + guard let strongSelf = self else { return Disposables.create() } + // Observable which will emit next element, when peripheral is discovered. + let disposable = strongSelf.centralManager.rx_didDiscoverPeripheral + .flatMap { [weak self] (peripheral, advertisment, rssi) -> Observable in + guard let strongSelf = self else { throw BluetoothError.destroyed } + let peripheral = Peripheral(manager: strongSelf, peripheral: peripheral) + let advertismentData = AdvertisementData(advertisementData: advertisment) + return .just(ScannedPeripheral(peripheral: peripheral, + advertisementData: advertismentData, rssi: rssi)) + } + .subscribe(element) + + // Start scanning for devices + strongSelf.centralManager.scanForPeripherals(withServices: serviceUUIDs, options: options) + + return Disposables.create { [weak self] in + guard let strongSelf = self else { return } + // When disposed, stop all scans, and remove scanning operation from queue + if strongSelf.centralManager.state == .poweredOn { + strongSelf.centralManager.stopScan() + } + disposable.dispose() + do { strongSelf.lock.lock(); defer { strongSelf.lock.unlock() } + if let index = strongSelf.scanQueue.index(where: { $0 == scanOperationBox.value! }) { + strongSelf.scanQueue.remove(at: index) + } + } + } + } + .queueSubscribe(on: strongSelf.subscriptionQueue) + .publish() + .refCount() + + let scanOperation = ScanOperation(uuids: serviceUUIDs, observable: operation) + strongSelf.scanQueue.append(scanOperation) + + scanOperationBox.value = scanOperation + return operation + }() + // Allow scanning as long as bluetooth is powered on + return strongSelf.ensure(.poweredOn, observable: observable) + } + } + + // MARK: State + + /// Continuous state of `BluetoothManager` instance described by `BluetoothState` which is equivalent to [CBManagerState](https://developer.apple.com/reference/corebluetooth/cbmanager/1648600-state). + /// - returns: Observable that emits `Next` immediately after subscribtion with current state of Bluetooth. Later, + /// whenever state changes events are emitted. Observable is infinite : doesn't generate `Complete`. + public var rx_state: Observable { + return .deferred { [weak self] in + guard let `self` = self else { throw BluetoothError.destroyed } + return self.centralManager.rx_didUpdateState.startWith(self.centralManager.state) + } + } + + /// Current state of `BluetoothManager` instance described by `BluetoothState` which is equivalent to [CBManagerState](https://developer.apple.com/reference/corebluetooth/cbmanager/1648600-state). + /// - returns: Current state of `BluetoothManager` as `BluetoothState`. + public var state: BluetoothState { + return centralManager.state + } + + // MARK: Peripheral's Connection Management + + /// Establishes connection with `Peripheral` after subscription to returned observable. It's user responsibility + /// to close connection with `cancelConnectionToPeripheral(_:)` after subscription was completed. Unsubscribing from + /// returned observable cancels connection attempt. By default observable is waiting infinitely for successful connection. + /// Additionally you can pass optional [dictionary](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCentralManager_Class/#//apple_ref/doc/constant_group/Peripheral_Connection_Options) + /// to customise the behaviour of connection. + /// - parameter peripheral: The `Peripheral` to which `BluetoothManager` is attempting to connect. + /// - parameter options: Dictionary to customise the behaviour of connection. + /// - returns: Observable which emits next and complete events after connection is established. + public func connect(_ peripheral: Peripheral, options: [String: Any]? = nil) + -> Observable { + + let success = centralManager.rx_didConnectPeripheral + .filter { $0 == peripheral.peripheral } + .take(1) + .map { _ in return peripheral } + + let error = centralManager.rx_didFailToConnectPeripheral + .filter { $0.0 == peripheral.peripheral } + .take(1) + .map { (peripheral, error) -> Peripheral in + throw BluetoothError.peripheralConnectionFailed(Peripheral(manager: self, peripheral: peripheral), error) + } + + let observable = Observable.create { [weak self] observer in + guard let strongSelf = self else { + observer.onError(BluetoothError.destroyed) + return Disposables.create() + } + if let error = BluetoothError(state: strongSelf.centralManager.state) { + observer.onError(error) + return Disposables.create() + } + + guard !peripheral.isConnected else { + observer.onNext(peripheral) + observer.onCompleted() + return Disposables.create() + } + + let disposable = success.amb(error).subscribe(observer) + + strongSelf.centralManager.connect(peripheral.peripheral, options: options) + + return Disposables.create { [weak self] in + guard let strongSelf = self else { return } + if !peripheral.isConnected { + strongSelf.centralManager.cancelPeripheralConnection(peripheral.peripheral) + disposable.dispose() + } + } + } + + return ensure(.poweredOn, observable: observable) + } + + /// Cancels an active or pending local connection to a `Peripheral` after observable subscription. It is not guaranteed + /// that physical connection will be closed immediately as well and all pending commands will not be executed. + /// - parameter peripheral: The `Peripheral` to which the `BluetoothManager` is either trying to + /// connect or has already connected. + /// - returns: Observable which emits next and complete events when peripheral successfully cancelled connection. + public func cancelPeripheralConnection(_ peripheral: Peripheral) -> Observable { + let observable = Observable.create { [weak self] observer in + guard let strongSelf = self else { + observer.onError(BluetoothError.destroyed) + return Disposables.create() + } + let disposable = strongSelf.monitorDisconnection(for: peripheral).take(1).subscribe(observer) + strongSelf.centralManager.cancelPeripheralConnection(peripheral.peripheral) + return disposable + } + return ensure(.poweredOn, observable: observable) + } + + // MARK: Retrieving Lists of Peripherals + + /// Returns observable list of the `Peripheral`s which are currently connected to the `BluetoothManager` and contain all of the specified `Service`'s UUIDs. + /// - parameter serviceUUIDs: A list of `Service` UUIDs + /// - returns: Observable which emits retrieved `Peripheral`s. They are in connected state and contain all of the + /// `Service`s with UUIDs specified in the `serviceUUIDs` parameter. Just after that complete event is emitted + public func retrieveConnectedPeripherals(withServices serviceUUIDs: [CBUUID]) -> Observable<[Peripheral]> { + let observable = Observable<[Peripheral]>.deferred { [weak self] in + guard let strongSelf = self else { throw BluetoothError.destroyed } + return strongSelf.centralManager.retrieveConnectedPeripherals(withServices: serviceUUIDs) + .map { [weak self] (peripheralTable: [RxPeripheralType]) -> [Peripheral] in + guard let strongSelf = self else { throw BluetoothError.destroyed } + return peripheralTable.map { + Peripheral(manager: strongSelf, peripheral: $0) + } + } + } + return ensure(.poweredOn, observable: observable) + } + + /// Returns observable list of `Peripheral`s by their identifiers which are known to `BluetoothManager`. + /// - parameter identifiers: List of `Peripheral`'s identifiers which should be retrieved. + /// - returns: Observable which emits next and complete events when list of `Peripheral`s are retrieved. + public func retrievePeripherals(withIdentifiers identifiers: [UUID]) -> Observable<[Peripheral]> { + let observable = Observable<[Peripheral]>.deferred { [weak self] in + guard let strongSelf = self else { throw BluetoothError.destroyed } + return strongSelf.centralManager.retrievePeripherals(withIdentifiers: identifiers) + .map { [weak self] (peripheralTable: [RxPeripheralType]) -> [Peripheral] in + guard let strongSelf = self else { throw BluetoothError.destroyed } + return peripheralTable.map { + Peripheral(manager: strongSelf, peripheral: $0) + } + } + } + return ensure(.poweredOn, observable: observable) + } + + // MARK: Internal functions + + /// Ensure that `state` is and will be the only state of `BluetoothManager` during subscription. + /// Otherwise error is emitted. + /// - parameter state: `BluetoothState` which should be present during subscription. + /// - parameter observable: Observable into which potential errors should be merged. + /// - returns: New observable which merges errors with source observable. + func ensure(_ state: BluetoothState, observable: Observable) -> Observable { + let statesObservable = rx_state + .filter { $0 != state && BluetoothError(state: $0) != nil } + .map { state -> T in throw BluetoothError(state: state)! } + return .absorb(statesObservable, observable) + } + + /// Ensure that specified `peripheral` is connected during subscription. + /// - parameter peripheral: `Peripheral` which should be connected during subscription. + /// - returns: Observable which emits error when `peripheral` is disconnected during subscription. + func ensurePeripheralIsConnected(_ peripheral: Peripheral) -> Observable { + return .deferred { + if !peripheral.isConnected { + throw BluetoothError.peripheralDisconnected(peripheral, nil) + } + return self.centralManager.rx_didDisconnectPeripheral + .filter { $0.0 == peripheral.peripheral } + .map { (_, error) -> T in + throw BluetoothError.peripheralDisconnected(peripheral, error) + } + } + } + + /// Emits `Peripheral` instance when it's connected. + /// - Parameter peripheral: `Peripheral` which is monitored for connection. + /// - Returns: Observable which emits next events when `peripheral` was connected. + public func monitorConnection(for peripheral: Peripheral) -> Observable { + return monitorPeripheral(on: centralManager.rx_didConnectPeripheral, peripheral: peripheral) + } + + /// Emits `Peripheral` instance when it's disconnected. + /// - Parameter peripheral: `Peripheral` which is monitored for disconnection. + /// - Returns: Observable which emits next events when `peripheral` was disconnected. + public func monitorDisconnection(for peripheral: Peripheral) -> Observable { + return monitorPeripheral(on: centralManager.rx_didDisconnectPeripheral.map { $0.0 }, peripheral: peripheral) + } + + func monitorPeripheral(on peripheralAction: Observable, peripheral: Peripheral) + -> Observable { + let observable = + peripheralAction + .filter { $0 == peripheral.peripheral } + .map { _ in peripheral } + return ensure(.poweredOn, observable: observable) + } + + #if os(iOS) + /// Emits `RestoredState` instance, when state of `BluetoothManager` has been restored, + /// Should only be called once in the lifetime of the app + /// - Returns: Observable which emits next events state has been restored + public func listenOnRestoredState() -> Observable { + return centralManager + .rx_willRestoreState + .take(1) + .flatMap { [weak self] dict -> Observable in + guard let strongSelf = self else { throw BluetoothError.destroyed } + return .just(RestoredState(restoredStateDictionary: dict, bluetoothManager: strongSelf)) + } + } + #endif +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/BluetoothState.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/BluetoothState.swift new file mode 100644 index 000000000..ac867e3d6 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/BluetoothState.swift @@ -0,0 +1,12 @@ +import Foundation + +/// Type describing bluetooth state, equivalent to +/// [CBManagerState](https://developer.apple.com/documentation/corebluetooth/cbmanagerstate). +public enum BluetoothState: Int { + case unknown + case resetting + case unsupported + case unauthorized + case poweredOff + case poweredOn +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Boxes.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Boxes.swift new file mode 100644 index 000000000..486feee05 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Boxes.swift @@ -0,0 +1,63 @@ +import Foundation + +class WeakBox: CustomDebugStringConvertible { + weak var value: T? + init() {} + init(value: T) { + self.value = value + } +} + +extension WeakBox { + var debugDescription: String { + return "WeakBox(\(String(describing: value)))" + } +} + +/// `ThreadSafeBox` is a helper class that allows use of resource (value) in a thread safe manner. +/// All read and write calls are wrapped in concurrent `DispatchQueue` which protects writing to +/// resource from more than 1 thread at a time. +class ThreadSafeBox: CustomDebugStringConvertible { + private let queue = DispatchQueue(label: "com.polidea.RxBluetoothKit.ThreadSafeBox") + fileprivate var value: T + init(value: T) { + self.value = value + } + + func read(_ block: (T) -> Result) -> Result { + var result: Result! = nil + queue.sync { + result = block(value) + } + return result + } + + func write(_ block: @escaping (inout T) -> Void) { + queue.async { + block(&self.value) + } + } + + func writeSync(_ block: @escaping (inout T) -> Void) { + queue.sync { + block(&self.value) + } + } + + @discardableResult func compareAndSet(compare: (T) -> Bool, set: @escaping (inout T) -> Void) -> Bool { + var result: Bool = false + queue.sync { + result = compare(value) + if result { + set(&self.value) + } + } + return result + } +} + +extension ThreadSafeBox { + var debugDescription: String { + return "ThreadSafeBox(\(String(describing: value)))" + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/CBCentral+Uuid.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/CBCentral+Uuid.swift new file mode 100644 index 000000000..223daedf6 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/CBCentral+Uuid.swift @@ -0,0 +1,9 @@ +import Foundation +import CoreBluetooth + +extension CBCentral { + /// There is still no identifier property for macOS, that's why we need to retrieve it by value method + var uuidIdentifier: UUID { + return value(forKey: "identifier") as! NSUUID as UUID + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/CBCentralManagerDelegateWrapper.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/CBCentralManagerDelegateWrapper.swift new file mode 100644 index 000000000..e03622886 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/CBCentralManagerDelegateWrapper.swift @@ -0,0 +1,75 @@ +import Foundation +import CoreBluetooth + + +class CBCentralManagerDelegateWrapper: NSObject, CBCentralManagerDelegate { + + let didUpdateState = PublishSubject() + let willRestoreState = ReplaySubject<[String: Any]>.create(bufferSize: 1) + let didDiscoverPeripheral = PublishSubject<(CBPeripheral, [String: Any], NSNumber)>() + let didConnectPeripheral = PublishSubject() + let didFailToConnectPeripheral = PublishSubject<(CBPeripheral, Error?)>() + let didDisconnectPeripheral = PublishSubject<(CBPeripheral, Error?)>() + let didUpdateANCSAuthorizationForPeripheral = PublishSubject<(CBPeripheral)>() + + func centralManagerDidUpdateState(_ central: CBCentralManager) { + guard let bleState = BluetoothState(rawValue: central.state.rawValue) else { return } + RxBluetoothKitLog.d("\(central.logDescription) didUpdateState(state: \(bleState.logDescription))") + didUpdateState.onNext(bleState) + } + + func centralManager(_ central: CBCentralManager, willRestoreState dict: [String: Any]) { + RxBluetoothKitLog.d("\(central.logDescription) willRestoreState(restoredState: \(dict))") + willRestoreState.onNext(dict) + } + + func centralManager(_ central: CBCentralManager, + didDiscover peripheral: CBPeripheral, + advertisementData: [String: Any], + rssi: NSNumber) { + RxBluetoothKitLog.d(""" + \(central.logDescription) didDiscover(peripheral: \(peripheral.logDescription), + rssi: \(rssi)) + """) + didDiscoverPeripheral.onNext((peripheral, advertisementData, rssi)) + } + + func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { + RxBluetoothKitLog.d(""" + \(central.logDescription) didConnect(to: \(peripheral.logDescription)) + """) + didConnectPeripheral.onNext(peripheral) + } + + func centralManager(_ central: CBCentralManager, + didFailToConnect peripheral: CBPeripheral, + error: Error?) { + RxBluetoothKitLog.d(""" + \(central.logDescription) didFailToConnect(to: \(peripheral.logDescription), + error: \(String(describing: error))) + """) + didFailToConnectPeripheral.onNext((peripheral, error)) + } + + func centralManager(_ central: CBCentralManager, + didDisconnectPeripheral peripheral: CBPeripheral, + error: Error?) { + RxBluetoothKitLog.d(""" + \(central.logDescription) didDisconnect(from: \(peripheral.logDescription), + error: \(String(describing: error))) + """) + didDisconnectPeripheral.onNext((peripheral, error)) + } + + #if !os(macOS) + @available(iOS 13.0, watchOS 6.0, tvOS 13.0, *) + func centralManager(_ central: CBCentralManager, + didUpdateANCSAuthorizationFor peripheral: CBPeripheral) { + RxBluetoothKitLog.d(""" + \(central.logDescription) didUpdateANCSAuthorizationFor + (peripheral: \(peripheral.logDescription) + """) + didUpdateANCSAuthorizationForPeripheral.onNext(peripheral) + } + #endif +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/CBPeripheralDelegateWrapper.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/CBPeripheralDelegateWrapper.swift new file mode 100644 index 000000000..6ebaf6ad9 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/CBPeripheralDelegateWrapper.swift @@ -0,0 +1,163 @@ +import Foundation +import CoreBluetooth + +class CBPeripheralDelegateWrapper: NSObject, CBPeripheralDelegate { + + let peripheralDidUpdateName = PublishSubject() + let peripheralDidModifyServices = PublishSubject<([CBService])>() + let peripheralDidReadRSSI = PublishSubject<(Int, Error?)>() + let peripheralDidDiscoverServices = PublishSubject<([CBService]?, Error?)>() + let peripheralDidDiscoverIncludedServicesForService = PublishSubject<(CBService, Error?)>() + let peripheralDidDiscoverCharacteristicsForService = PublishSubject<(CBService, Error?)>() + let peripheralDidUpdateValueForCharacteristic = PublishSubject<(CBCharacteristic, Error?)>() + let peripheralDidWriteValueForCharacteristic = PublishSubject<(CBCharacteristic, Error?)>() + let peripheralDidUpdateNotificationStateForCharacteristic = + PublishSubject<(CBCharacteristic, Error?)>() + let peripheralDidDiscoverDescriptorsForCharacteristic = + PublishSubject<(CBCharacteristic, Error?)>() + let peripheralDidUpdateValueForDescriptor = PublishSubject<(CBDescriptor, Error?)>() + let peripheralDidWriteValueForDescriptor = PublishSubject<(CBDescriptor, Error?)>() + let peripheralIsReadyToSendWriteWithoutResponse = PublishSubject() + let peripheralDidOpenL2CAPChannel = PublishSubject<(Any?, Error?)>() + + func peripheralDidUpdateName(_ peripheral: CBPeripheral) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didUpdateName(name: \(String(describing: peripheral.name))) + """) + peripheralDidUpdateName.onNext(peripheral.name) + } + + func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didModifyServices(services: + [\(invalidatedServices.logDescription))] + """) + peripheralDidModifyServices.onNext(invalidatedServices) + } + + func peripheral(_ peripheral: CBPeripheral, didReadRSSI rssi: NSNumber, error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didReadRSSI(rssi: \(rssi), + error: \(String(describing: error))) + """) + peripheralDidReadRSSI.onNext((rssi.intValue, error)) + } + + func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didDiscoverServices(services + : \(String(describing: peripheral.services?.logDescription)), + error: \(String(describing: error))) + """) + peripheralDidDiscoverServices.onNext((peripheral.services, error)) + } + + func peripheral(_ peripheral: CBPeripheral, + didDiscoverIncludedServicesFor service: CBService, + error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didDiscoverIncludedServices(for: + \(service.logDescription), includedServices: + \(String(describing: service.includedServices?.logDescription)), + error: \(String(describing: error))) + """) + peripheralDidDiscoverIncludedServicesForService.onNext((service, error)) + } + + func peripheral(_ peripheral: CBPeripheral, + didDiscoverCharacteristicsFor service: CBService, + error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didDiscoverCharacteristicsFor(for: + \(service.logDescription), characteristics: + \(String(describing: service.characteristics?.logDescription)), + error: \(String(describing: error))) + """) + peripheralDidDiscoverCharacteristicsForService.onNext((service, error)) + } + + func peripheral(_ peripheral: CBPeripheral, + didUpdateValueFor characteristic: CBCharacteristic, + error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didUpdateValueFor(for:\(characteristic.logDescription), + value: \(String(describing: characteristic.value?.logDescription)), + error: \(String(describing: error))) + """) + peripheralDidUpdateValueForCharacteristic + .onNext((characteristic, error)) + } + + func peripheral(_ peripheral: CBPeripheral, + didWriteValueFor characteristic: CBCharacteristic, + error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didWriteValueFor(for:\(characteristic.logDescription), + value: \(String(describing: characteristic.value?.logDescription)), + error: \(String(describing: error))) + """) + peripheralDidWriteValueForCharacteristic + .onNext((characteristic, error)) + } + + func peripheral(_ peripheral: CBPeripheral, + didUpdateNotificationStateFor characteristic: CBCharacteristic, + error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didUpdateNotificationStateFor( + for:\(characteristic.logDescription), isNotifying: \(characteristic.isNotifying), + error: \(String(describing: error))) + """) + peripheralDidUpdateNotificationStateForCharacteristic + .onNext((characteristic, error)) + } + + func peripheral(_ peripheral: CBPeripheral, + didDiscoverDescriptorsFor characteristic: CBCharacteristic, + error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didDiscoverDescriptorsFor + (for:\(characteristic.logDescription), descriptors: + \(String(describing: characteristic.descriptors?.logDescription)), + error: \(String(describing: error))) + """) + peripheralDidDiscoverDescriptorsForCharacteristic + .onNext((characteristic, error)) + } + + func peripheral(_ peripheral: CBPeripheral, + didUpdateValueFor descriptor: CBDescriptor, + error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didUpdateValueFor(for:\(descriptor.logDescription), + value: \(String(describing: descriptor.value)), error: \(String(describing: error))) + """) + peripheralDidUpdateValueForDescriptor.onNext((descriptor, error)) + } + + func peripheral(_ peripheral: CBPeripheral, + didWriteValueFor descriptor: CBDescriptor, + error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didWriteValueFor(for:\(descriptor.logDescription), + error: \(String(describing: error))) + """) + peripheralDidWriteValueForDescriptor.onNext((descriptor, error)) + } + + func peripheralIsReady(toSendWriteWithoutResponse peripheral: CBPeripheral) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) peripheralIsReady(toSendWriteWithoutResponse) + """) + peripheralIsReadyToSendWriteWithoutResponse.onNext(()) + } + + @available(OSX 10.13, iOS 11, *) + func peripheral(_ peripheral: CBPeripheral, didOpen channel: CBL2CAPChannel?, error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didOpenL2CAPChannel(for:\(peripheral.logDescription), + error: \(String(describing: error))) + """) + peripheralDidOpenL2CAPChannel.onNext((channel, error)) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Characteristic.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Characteristic.swift new file mode 100644 index 000000000..ee3258a7c --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Characteristic.swift @@ -0,0 +1,121 @@ +import Foundation +import CoreBluetooth + +// swiftlint:disable line_length + +/// Characteristic is a class implementing ReactiveX which wraps CoreBluetooth functions related to interaction with [CBCharacteristic](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCharacteristic_Class/) +public class Characteristic { + let characteristic: RxCharacteristicType + /// Service which contains this characteristic + public let service: Service + + /// Current value of characteristic. If value is not present - it's `nil`. + public var value: Data? { + return characteristic.value + } + + /// Unique identifier of an object. + public var objectId: UInt { + return characteristic.objectId + } + + /// The Bluetooth UUID of the `Characteristic` instance. + public var uuid: CBUUID { + return characteristic.uuid + } + + /// Flag which is set to true if characteristic is currently notifying + public var isNotifying: Bool { + return characteristic.isNotifying + } + + /// Properties of characteristic. For more info about this refer to [CBCharacteristicProperties](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCharacteristic_Class/#//apple_ref/c/tdef/CBCharacteristicProperties) + public var properties: CBCharacteristicProperties { + return characteristic.properties + } + + /// Value of this property is an array of `Descriptor` objects. They provide more detailed information about characteristics value. + public var descriptors: [Descriptor]? { + return characteristic.descriptors?.map { Descriptor(descriptor: $0, characteristic: self) } + } + + init(characteristic: RxCharacteristicType, service: Service) { + self.characteristic = characteristic + self.service = service + } + + /// Function that triggers descriptors discovery for characteristic. + /// - returns: Observable that emits `Next` with array of `Descriptor` instances, once they're discovered. + /// Immediately after that `.Complete` is emitted. + public func discoverDescriptors() -> Observable<[Descriptor]> { + return service.peripheral.discoverDescriptors(for: self) + } + + /// Function that allow to monitor writes that happened for characteristic. + /// - Returns: Observable that emits `Next` with `Characteristic` instance every time when write has happened. + /// It's **infinite** stream, so `.Complete` is never called. + public func monitorWrite() -> Observable { + return service.peripheral.monitorWrite(for: self) + } + + /// Function that triggers write of data to characteristic. Write is called after subscribtion to `Observable` is made. + /// Behavior of this function strongly depends on [CBCharacteristicWriteType](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBPeripheral_Class/#//apple_ref/swift/enum/c:@E@CBCharacteristicWriteType), so be sure to check this out before usage of the method. + /// - parameter forCharacteristic: `Descriptor` instance to write value to. + /// - parameter type: Type of write operation. Possible values: `.WithResponse`, `.WithoutResponse` + /// - returns: Observable that emition depends on `CBCharacteristicWriteType` passed to the function call. + /// Behavior is following: + /// + /// - `WithResponse` - Observable emits `Next` with `Characteristic` instance write was confirmed without any errors. + /// Immediately after that `Complete` is called. If any problem has happened, errors are emitted. + /// - `WithoutResponse` - Observable emits `Next` with `Characteristic` instance once write was called. + /// Immediately after that `.Complete` is called. Result of this call is not checked, so as a user you are not sure + /// if everything completed successfully. Errors are not emitted + public func writeValue(_ data: Data, type: CBCharacteristicWriteType) -> Observable { + return service.peripheral.writeValue(data, for: self, type: type) + } + + /// Function that allow to monitor value updates for `Characteristic` instance. + /// - Returns: Observable that emits `Next` with `Characteristic` instance every time when value has changed. + /// It's **infinite** stream, so `.Complete` is never called. + public func monitorValueUpdate() -> Observable { + return service.peripheral.monitorValueUpdate(for: self) + } + + /// Function that triggers read of current value of the `Characteristic` instance. + /// Read is called after subscription to `Observable` is made. + /// - Returns: Observable which emits `Next` with given characteristic when value is ready to read. Immediately after that + /// `.Complete` is emitted. + public func readValue() -> Observable { + return service.peripheral.readValue(for: self) + } + + /// Function that triggers set of notification state of the `Characteristic`. + /// This change is called after subscribtion to `Observable` is made. + /// - warning: This method is not responsible for emitting values every time that `Characteristic` value is changed. + /// For this, refer to other method: `monitorValueUpdateForCharacteristic(_)`. These two are often called together. + /// - parameter enabled: New value of notifications state. Specify `true` if you're interested in getting values + /// - returns: Observable which emits `Next` with Characteristic that state was changed. Immediately after `.Complete` is emitted + public func setNotifyValue(_ enabled: Bool) -> Observable { + return service.peripheral.setNotifyValue(enabled, for: self) + } + + /// Function that triggers set of notification state of the `Characteristic`, and monitor for any incoming updates. + /// Notification is set after subscribtion to `Observable` is made. + /// - returns: Observable which emits `Next`, when characteristic value is updated. + /// This is **infinite** stream of values. + + public func setNotificationAndMonitorUpdates() -> Observable { + return service.peripheral.setNotificationAndMonitorUpdates(for: self) + } +} + +extension Characteristic: Equatable {} + +/// Compare two characteristics. Characteristics are the same when their UUIDs are the same. +/// +/// - parameter lhs: First characteristic to compare +/// - parameter rhs: Second characteristic to compare +/// - returns: True if both characteristics are the same. +public func == (lhs: Characteristic, rhs: Characteristic) -> Bool { + return lhs.characteristic == rhs.characteristic +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Descriptor.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Descriptor.swift new file mode 100644 index 000000000..ec957ce3b --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Descriptor.swift @@ -0,0 +1,74 @@ +import Foundation +import CoreBluetooth + +/// Descriptor is a class implementing ReactiveX which wraps CoreBluetooth functions related to interaction with +/// [CBDescriptor](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBDescriptor_Class/) +/// Descriptors provide more information about a characteristic’s value. +public class Descriptor { + + let descriptor: RxDescriptorType + + /// Characteristic to which this descriptor belongs. + public let characteristic: Characteristic + + /// Unique identifier of an object. + public var objectId: UInt { + return descriptor.objectId + } + + /// The Bluetooth UUID of the `Descriptor` instance. + public var uuid: CBUUID { + return descriptor.uuid + } + + /// The value of the descriptor. It can be written and read through functions on `Descriptor` instance. + public var value: Any? { + return descriptor.value + } + + init(descriptor: RxDescriptorType, characteristic: Characteristic) { + self.descriptor = descriptor + self.characteristic = characteristic + } + + /// Function that allow to monitor writes that happened for descriptor. + /// - Returns: Observable that emits `Next` with `Descriptor` instance every time when write has happened. + /// It's **infinite** stream, so `.Complete` is never called. + public func monitorWrite() -> Observable { + return characteristic.service.peripheral.monitorWrite(for: self) + } + + /// Function that triggers write of data to descriptor. Write is called after subscribtion to `Observable` is made. + /// - Parameter data: `NSData` that'll be written to `Descriptor` instance + /// - Returns: Observable that emits `Next` with `Descriptor` instance, once value is written successfully. + /// Immediately after that `.Complete` is emitted. + public func writeValue(_ data: Data) -> Observable { + return characteristic.service.peripheral.writeValue(data, for: self) + } + + /// Function that allow to monitor value updates for `Descriptor` instance. + /// - Returns: Observable that emits `Next` with `Descriptor` instance every time when value has changed. + /// It's **infinite** stream, so `.Complete` is never called. + public func monitorValueUpdate() -> Observable { + return characteristic.service.peripheral.monitorValueUpdate(for: self) + } + + /// Function that triggers read of current value of the `Descriptor` instance. + /// Read is called after subscription to `Observable` is made. + /// - Returns: Observable which emits `Next` with given descriptor when value is ready to read. + /// Immediately after that `.Complete` is emitted. + public func readValue() -> Observable { + return characteristic.service.peripheral.readValue(for: self) + } +} + +extension Descriptor: Equatable {} + +/// Compare two descriptors. Descriptors are the same when their UUIDs are the same. +/// +/// - parameter lhs: First descriptor to compare +/// - parameter rhs: Second descriptor to compare +/// - returns: True if both descriptor are the same. +public func == (lhs: Descriptor, rhs: Descriptor) -> Bool { + return lhs.descriptor == rhs.descriptor +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/DeviceIdentifiers.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/DeviceIdentifiers.swift new file mode 100644 index 000000000..41fb113df --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/DeviceIdentifiers.swift @@ -0,0 +1,51 @@ +import CoreBluetooth + +/// ServiceIdentifier protocol specifies how information about services of device should look like. +/// Sample implementation could look like: +/// +/// ``` +/// enum DeviceService: String, ServiceIdentifier { +/// case deviceInformation = "180A" +/// var uuid: CBUUID { +/// return CBUUID(string: self.rawValue) +/// } +/// } +/// ``` +/// After implementing this and other protocol `CharacteristicIdentifier, you could call methods even easier +/// thanks to convenience methods in library. This methods do all of the heavy lifting like discovering services, taking +/// them from cache etc. for you. We really recommend you to use it. +public protocol ServiceIdentifier { + /// Unique identifier of a service. + var uuid: CBUUID { get } +} + +/// Characteristic protocol specifies how information about characteristics of device should look like. +/// Sample implementation could look like: +/// ``` +/// enum DeviceCharacteristic: String, CharacteristicIdentifier { +/// case manufacturerName = "2A29" +/// var uuid: CBUUID { +/// return CBUUID(string: self.rawValue) +/// } +/// var service: ServiceIdentifier { +/// switch self { +/// case .ManufacturerName: +/// return XXXService.DeviceInformation +/// } +/// } +/// } +/// ``` +public protocol CharacteristicIdentifier { + /// Unique identifier of a characteristic. + var uuid: CBUUID { get } + /// `ServiceIdentifier` instance that this characteristic belongs to. + var service: ServiceIdentifier { get } +} + +/// DescriptorIdentifier protocol specifies how information about descriptors of device should look like. +public protocol DescriptorIdentifier { + /// Unique identifier of a descriptor. + var uuid: CBUUID { get } + /// `CharacteristicIdentifier` instance that this descriptor belongs to. + var characteristic: CharacteristicIdentifier { get } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Logging.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Logging.swift new file mode 100644 index 000000000..05a742c5e --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Logging.swift @@ -0,0 +1,218 @@ +import Foundation +import CoreBluetooth + +/** + RxBluetoothKit specific logging class which gives access to its settings. + */ +public class RxBluetoothKitLog: ReactiveCompatible { + + fileprivate static var currentLogLevel: LogLevel = .none + + fileprivate static let subject = PublishSubject() + + private init() { + } + + /// Log levels for internal logging mechanism. + public enum LogLevel: UInt8 { + /// Logging is disabled + case none = 255 + /// All logs are monitored. + case verbose = 0 + /// Only debug logs and of higher importance are logged. + case debug = 1 + /// Only info logs and of higher importance are logged. + case info = 2 + /// Only warning logs and of higher importance are logged. + case warning = 3 + /// Only error logs and of higher importance are logged. + case error = 4 + } + + /** + * Set new log level. + * - Parameter logLevel: New log level to be applied. + */ + public static func setLogLevel(_ logLevel: LogLevel) { + currentLogLevel = logLevel + } + + /** + * Get current log level. + * - Returns: Currently set log level. + */ + public static func getLogLevel() -> LogLevel { + return currentLogLevel + } + + fileprivate static func tag(with logLevel: LogLevel) -> String { + let prefix: String + + switch logLevel { + case .none: + prefix = "[RxBLEKit|NONE|" + case .verbose: + prefix = "[RxBLEKit|VERB|" + case .debug: + prefix = "[RxBLEKit|DEBG|" + case .info: + prefix = "[RxBLEKit|INFO|" + case .warning: + prefix = "[RxBLEKit|WARN|" + case .error: + prefix = "[RxBLEKit|ERRO|" + } + let time = Date().timeIntervalSinceReferenceDate + return prefix + String(format: "%02.0f:%02.0f:%02.0f.%03.f]:", + floor(time / 3600.0).truncatingRemainder(dividingBy: 24), + floor(time / 60.0).truncatingRemainder(dividingBy: 60), + floor(time).truncatingRemainder(dividingBy: 60), + floor(time * 1000).truncatingRemainder(dividingBy: 1000)) + } + + fileprivate static func log(with logLevel: LogLevel, message: @autoclosure () -> String) { + if currentLogLevel <= logLevel { + let string = "\(tag(with: logLevel)) \(message())" + subject.onNext(string) + print(string) + } + } + + static func v(_ message: @autoclosure () -> String) { + log(with: .verbose, message: message()) + } + + static func d(_ message: @autoclosure () -> String) { + log(with: .debug, message: message()) + } + + static func i(_ message: @autoclosure () -> String) { + log(with: .info, message: message()) + } + + static func w(_ message: @autoclosure () -> String) { + log(with: .warning, message: message()) + } + + static func e(_ message: @autoclosure () -> String) { + log(with: .error, message: message()) + } +} + +extension RxBluetoothKitLog.LogLevel: Comparable { + public static func < (lhs: RxBluetoothKitLog.LogLevel, rhs: RxBluetoothKitLog.LogLevel) -> Bool { + return lhs.rawValue < rhs.rawValue + } + + public static func <= (lhs: RxBluetoothKitLog.LogLevel, rhs: RxBluetoothKitLog.LogLevel) -> Bool { + return lhs.rawValue <= rhs.rawValue + } + + public static func > (lhs: RxBluetoothKitLog.LogLevel, rhs: RxBluetoothKitLog.LogLevel) -> Bool { + return lhs.rawValue > rhs.rawValue + } + + public static func >= (lhs: RxBluetoothKitLog.LogLevel, rhs: RxBluetoothKitLog.LogLevel) -> Bool { + return lhs.rawValue >= rhs.rawValue + } + + public static func == (lhs: RxBluetoothKitLog.LogLevel, rhs: RxBluetoothKitLog.LogLevel) -> Bool { + return lhs.rawValue == rhs.rawValue + } +} + +protocol Loggable { + var logDescription: String { get } +} + +extension Data: Loggable { + var logDescription: String { + return map { String(format: "%02x", $0) }.joined() + } +} + +extension BluetoothState: Loggable { + var logDescription: String { + switch self { + case .unknown: return "unknown" + case .resetting: return "resetting" + case .unsupported: return "unsupported" + case .unauthorized: return "unauthorized" + case .poweredOff: return "poweredOff" + case .poweredOn: return "poweredOn" + } + } +} + +extension CBCharacteristicWriteType: Loggable { + var logDescription: String { + switch self { + case .withResponse: return "withResponse" + case .withoutResponse: return "withoutResponse" + } + } +} + +extension UUID: Loggable { + var logDescription: String { + return uuidString + } +} + +extension CBUUID: Loggable { + @objc var logDescription: String { + return uuidString + } +} + +extension CBCentralManager: Loggable { + @objc var logDescription: String { + return "CentralManager(\(UInt(bitPattern: ObjectIdentifier(self))))" + } +} + +extension CBPeripheral: Loggable { + @objc var logDescription: String { + return "Peripheral(uuid: \(value(forKey: "identifier") as! NSUUID as UUID), name: \(String(describing: name)))" + } +} + +extension CBCharacteristic: Loggable { + @objc var logDescription: String { + return "Characteristic(uuid: \(uuid), id: \((UInt(bitPattern: ObjectIdentifier(self)))))" + } +} + +extension CBService: Loggable { + @objc var logDescription: String { + return "Service(uuid: \(uuid), id: \((UInt(bitPattern: ObjectIdentifier(self)))))" + } +} + +extension CBDescriptor: Loggable { + @objc var logDescription: String { + return "Descriptor(uuid: \(uuid), id: \((UInt(bitPattern: ObjectIdentifier(self)))))" + } +} + +extension Array where Element: Loggable { + var logDescription: String { + return "[\(map { $0.logDescription }.joined(separator: ", "))]" + } +} + +extension Reactive where Base == RxBluetoothKitLog { + /** + * This is continuous value, which emits before a log is printed to standard output. + * + * - it never fails + * - it delivers events on `MainScheduler.instance` + * - `share(scope: .whileConnected)` sharing strategy + */ + public var log: Observable { + return RxBluetoothKitLog.subject.asObserver() + .observeOn(MainScheduler.instance) + .catchErrorJustReturn("") + .share(scope: .whileConnected) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/ManagerType.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/ManagerType.swift new file mode 100644 index 000000000..cd4b1d1a0 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/ManagerType.swift @@ -0,0 +1,41 @@ +import Foundation +import CoreBluetooth + +public protocol ManagerType: AnyObject { + associatedtype Manager + + /// Implementation of CBManager + var manager: Manager { get } + /// Current state of `CentralManager` instance described by `BluetoothState` which is equivalent to + /// [CBManagerState](https://developer.apple.com/documentation/corebluetooth/cbmanagerstate). + var state: BluetoothState { get } + + /// Continuous state of `CBManager` instance described by `BluetoothState` which is equivalent to [CBManagerState](https://developer.apple.com/documentation/corebluetooth/cbmanagerstate). + /// - returns: Observable that emits `next` event whenever state changes. + /// + /// It's **infinite** stream, so `.complete` is never called. + func observeState() -> Observable + + /// Continuous state of `CBManager` instance described by `BluetoothState` which is equivalent to [CBManagerState](https://developer.apple.com/documentation/corebluetooth/cbmanagerstate). + /// - returns: Observable that emits `next` event starting with current state and whenever state changes. + /// + /// It's **infinite** stream, so `.complete` is never called. + func observeStateWithInitialValue() -> Observable +} + +public extension ManagerType { + /// Ensure that `state` is and will be the only state of `CentralManager` during subscription. + /// Otherwise error is emitted. + /// - parameter state: `BluetoothState` which should be present during subscription. + /// - parameter observable: Observable into which potential errors should be merged. + /// - returns: New observable which merges errors with source observable. + func ensure(_ state: BluetoothState, observable: Observable) -> Observable { + return .deferred { [weak self] in + guard let strongSelf = self else { throw BluetoothError.destroyed } + let statesObservable = strongSelf.observeStateWithInitialValue() + .filter { $0 != state && BluetoothError(state: $0) != nil } + .map { state -> T in throw BluetoothError(state: state)! } + return .absorb(statesObservable, observable) + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Observable+Absorb.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Observable+Absorb.swift new file mode 100644 index 000000000..e124e702b --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Observable+Absorb.swift @@ -0,0 +1,25 @@ +extension ObservableType { + /// Absorbes all of events from a and b observables into result observable. + + /// - parameter a: First observable + /// - parameter b: Second observable + /// - returns: New observable which emits all of events from a and b observables. + /// If error or complete is received on any of the observables, it's propagates immediately to result observable + static func absorb(_ a: Observable, _ b: Observable) -> Observable { + return .create { observer in + let disposable = CompositeDisposable() + let innerObserver: AnyObserver = AnyObserver { event in + observer.on(event) + if event.isStopEvent { + disposable.dispose() + } + } + _ = disposable.insert(a.subscribe(innerObserver)) + if !disposable.isDisposed { + _ = disposable.insert(b.subscribe(innerObserver)) + } + + return disposable + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Observable+QueueSubscribeOn.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Observable+QueueSubscribeOn.swift new file mode 100644 index 000000000..267f1a74c --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Observable+QueueSubscribeOn.swift @@ -0,0 +1,125 @@ +import Foundation + +/// Queue which is used for queueing subscriptions for queueSubscribeOn operator. +class SerializedSubscriptionQueue { + let lock = NSLock() + + /// First element on queue is curently subscribed and not completed + /// observable. All others are queued for subscription when the first + /// one is finished. + var queue: [DelayedObservableType] = [] + + /// Queue subscription. If observable is inserted + /// into empty queue it's subscribed immediately. Otherwise + /// it waits for completion from other observables. + func queueSubscription(observable: DelayedObservableType) { + lock.lock(); defer { lock.unlock() } + let execute = queue.isEmpty + queue.append(observable) + if execute { + // Observable is scheduled immidiately + queue.first?.delayedSubscribe() + } + } + + func unsubscribe(observable: DelayedObservableType) { + lock.lock(); defer { lock.unlock() } + // Find index of observable which should be unsubscribed + // and remove it from queue + if let index = queue.index(where: { $0 === observable }) { + queue.remove(at: index) + // If first item was unsubscribed, subscribe on next one + // if available + if index == 0 { + queue.first?.delayedSubscribe() + } + } + } +} + +protocol DelayedObservableType: class { + func delayedSubscribe() +} + +class QueueSubscribeOn: Cancelable, ObservableType, ObserverType, DelayedObservableType { + typealias E = Element + + let source: Observable + let queue: SerializedSubscriptionQueue + var observer: AnyObserver? + + let serialDisposable = SerialDisposable() + var _isDisposed: Int32 = 0 + var isDisposed: Bool { + return _isDisposed == 1 + } + + var disposed: Bool { + return _isDisposed == 1 + } + + init(source: Observable, queue: SerializedSubscriptionQueue) { + self.source = source + self.queue = queue + } + + /// All event needs to be passed to original observer + /// if subscription was not disposed. If stream is completed + /// cleanup should occur. + func on(_ event: Event) { + guard !isDisposed else { return } + observer?.on(event) + if event.isStopEvent { + dispose() + } + } + + /// Part of producer implementation. We need to make sure that we can optimize + /// scheduling of a work (taken from RxSwift source code) + func subscribe(_ observer: O) -> Disposable where O.Element == Element { + if !CurrentThreadScheduler.isScheduleRequired { + return run(observer: observer) + } + return CurrentThreadScheduler.instance.schedule(()) { _ in + self.run(observer: observer) + } + } + + /// After original subscription we need to place it on queue for delayed execution if required. + func run(observer: O) -> Disposable where O.Element == Element { + self.observer = observer.asObserver() + queue.queueSubscription(observable: self) + return self + } + + /// Delayed subscription must be called after original subscription so that observer + /// will be stored by that time. + func delayedSubscribe() { + serialDisposable.disposable = self.source.subscribe(self) + } + + /// When this observable is disposed we need to remove it from queue to let other + /// observables to be able to subscribe. + func dispose() { + if OSAtomicCompareAndSwap32(0, 1, &_isDisposed) { + self.queue.unsubscribe(observable: self) + self.serialDisposable.dispose() + } + } +} + +extension ObservableType { + + // swiftlint:disable missing_docs + /// Store subscription in queue on which it will be executed sequentially. Subscribe method is called + /// only when there are no registered subscription on queue or last running observable completed its stream + /// or was disposed before that event. + /// - parameter queue: Queue on which scheduled subscriptions will be executed in sequentially. + /// - returns: The source which will be subscribe when queue is empty or previous + /// observable was completed or disposed. + func queueSubscribe(on queue: SerializedSubscriptionQueue) -> Observable { + return QueueSubscribeOn(source: asObservable(), queue: queue).asObservable() + } + + // swiftlint:enable missing_docs +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Peripheral+Convenience.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Peripheral+Convenience.swift new file mode 100644 index 000000000..ca6ce8247 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Peripheral+Convenience.swift @@ -0,0 +1,213 @@ +import Foundation +import CoreBluetooth + +// swiftlint:disable line_length + +extension Peripheral { + + /// Function used to receive service with given identifier. It's taken from cache if it's available, + /// or directly by `discoverServices` call + /// - Parameter identifier: Unique identifier of Service + /// - Returns: Observation which emits `Next` event, when specified service has been found. + /// Immediately after that `.Complete` is emitted. + public func service(with identifier: ServiceIdentifier) -> Observable { + return .deferred { [weak self] in + guard let strongSelf = self else { throw BluetoothError.destroyed } + if let services = strongSelf.services, + let service = services.first(where: { $0.uuid == identifier.uuid }) { + return .just(service) + } else { + return strongSelf.discoverServices([identifier.uuid]) + .flatMap { Observable.from($0) } + } + } + } + + /// Function used to receive characteristic with given identifier. If it's available it's taken from cache. + /// Otherwise - directly by `discoverCharacteristics` call + /// - Parameter identifier: Unique identifier of Characteristic, that has information + /// about service which characteristic belongs to. + /// - Returns: Observation which emits `Next` event, when specified characteristic has been found. + /// Immediately after that `.Complete` is emitted. + public func characteristic(with identifier: CharacteristicIdentifier) -> Observable { + return .deferred { [weak self] in + guard let strongSelf = self else { throw BluetoothError.destroyed } + return strongSelf.service(with: identifier.service) + .flatMap { service -> Observable in + if let characteristics = service.characteristics, let characteristic = characteristics.first(where: { + $0.uuid == identifier.uuid + }) { + return .just(characteristic) + } + return service.discoverCharacteristics([identifier.uuid]) + .flatMap { Observable.from($0) } + } + } + } + + /// Function used to receive descriptor with given identifier. If it's available it's taken from cache. + /// Otherwise - directly by `discoverDescriptor` call + /// - Parameter identifier: Unique identifier of Descriptor, that has information + /// about characteristic which descriptor belongs to. + /// - Returns: Observation which emits `Next` event, when specified descriptor has been found. + /// Immediately after that `.Complete` is emitted. + public func descriptor(with identifier: DescriptorIdentifier) -> Observable { + return .deferred { [weak self] in + guard let strongSelf = self else { throw BluetoothError.destroyed } + return strongSelf.characteristic(with: identifier.characteristic) + .flatMap { characteristic -> Observable in + if let descriptors = characteristic.descriptors, + let descriptor = descriptors.first(where: { $0.uuid == identifier.uuid }) { + return .just(descriptor) + } + return characteristic.discoverDescriptors() + .flatMap { Observable.from($0) } + .filter { $0.uuid == identifier.uuid } + .take(1) + } + } + } + + /// Function that allow to monitor writes that happened for characteristic. + /// - Parameter identifier: Identifier of characteristic of which value writes should be monitored. + /// - Returns: Observable that emits `Next` with `Characteristic` instance every time when write has happened. + /// It's **infinite** stream, so `.Complete` is never called. + public func monitorWrite(for identifier: CharacteristicIdentifier) + -> Observable { + return characteristic(with: identifier) + .flatMap { [weak self] in + self?.monitorWrite(for: $0) ?? .error(BluetoothError.destroyed) + } + } + + /// Function that triggers write of data to characteristic. Write is called after subscribtion to `Observable` is made. + /// Behavior of this function strongly depends on [CBCharacteristicWriteType](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBPeripheral_Class/#//apple_ref/swift/enum/c:@E@CBCharacteristicWriteType), so be sure to check this out before usage of the method. + /// - parameter data: Data that'll be written written to `Characteristic` instance + /// - parameter forCharacteristicWithIdentifier: unique identifier of service, which also holds information about service characteristic belongs to. + /// `Descriptor` instance to write value to. + /// - parameter type: Type of write operation. Possible values: `.WithResponse`, `.WithoutResponse` + /// - returns: Observable that emition depends on `CBCharacteristicWriteType` passed to the function call. + /// Behavior is following: + /// - `WithResponse` - Observable emits `Next` with `Characteristic` instance write was confirmed without any errors. + /// Immediately after that `Complete` is called. If any problem has happened, errors are emitted. + /// - `WithoutResponse` - Observable emits `Next` with `Characteristic` instance once write was called. + /// Immediately after that `.Complete` is called. Result of this call is not checked, so as a user you are not sure + /// if everything completed successfully. Errors are not emitted + public func writeValue(_ data: Data, for identifier: CharacteristicIdentifier, + type: CBCharacteristicWriteType) -> Observable { + return characteristic(with: identifier) + .flatMap { [weak self] in + self?.writeValue(data, for: $0, type: type) ?? .error(BluetoothError.destroyed) + } + } + + /// Function that allow to monitor value updates for `Characteristic` instance. + /// - Parameter identifier: unique identifier of service, which also holds information about service that characteristic belongs to. + /// - Returns: Observable that emits `Next` with `Characteristic` instance every time when value has changed. + /// It's **infinite** stream, so `.Complete` is never called. + public func monitorValueUpdate(for identifier: CharacteristicIdentifier) -> Observable { + return characteristic(with: identifier) + .flatMap { [weak self] in + self?.monitorValueUpdate(for: $0) ?? .error(BluetoothError.destroyed) + } + } + + /// Function that triggers read of current value of the `Characteristic` instance. + /// Read is called after subscription to `Observable` is made. + /// - Parameter identifier: unique identifier of service, which also holds information about service that characteristic belongs to. + /// - Returns: Observable which emits `Next` with given characteristic when value is ready to read. Immediately after that + /// `.Complete` is emitted. + public func readValue(for identifier: CharacteristicIdentifier) -> Observable { + return characteristic(with: identifier) + .flatMap { [weak self] in + self?.readValue(for: $0) ?? .error(BluetoothError.destroyed) + } + } + + /// Function that triggers set of notification state of the `Characteristic`. + /// This change is called after subscribtion to `Observable` is made. + /// - warning: This method is not responsible for emitting values every time that `Characteristic` value is changed. + /// For this, refer to other method: `monitorValueUpdateForCharacteristic(_)`. These two are often called together. + /// - parameter enabled: New value of notifications state. Specify `true` if you're interested in getting values + /// - parameter identifier: unique identifier of service, which also holds information about service that characteristic belongs to. + /// - returns: Observable which emits `Next` with Characteristic that state was changed. Immediately after `.Complete` is emitted + public func setNotifyValue(_ enabled: Bool, for identifier: CharacteristicIdentifier) + -> Observable { + return characteristic(with: identifier) + .flatMap { [weak self] in + self?.setNotifyValue(enabled, for: $0) ?? .error(BluetoothError.destroyed) + } + } + + /// Function that triggers set of notification state of the `Characteristic`, and monitor for any incoming updates. + /// Notification is set after subscribtion to `Observable` is made. + /// - parameter identifier: unique identifier of service, which also holds information about service that characteristic belongs to. + /// - returns: Observable which emits `Next`, when characteristic value is updated. + /// This is **infinite** stream of values. + public func setNotificationAndMonitorUpdates(for identifier: CharacteristicIdentifier) + -> Observable { + return characteristic(with: identifier) + .flatMap { [weak self] in + self?.setNotificationAndMonitorUpdates(for: $0) ?? .error(BluetoothError.destroyed) + } + } + + /// Function that triggers descriptors discovery for characteristic + /// - Parameter characteristic: `Characteristic` instance for which descriptors should be discovered. + /// - parameter identifier: unique identifier of descriptor, which also holds information about characteristic that descriptor belongs to. + /// - Returns: Observable that emits `Next` with array of `Descriptor` instances, once they're discovered. + /// Immediately after that `.Complete` is emitted. + public func discoverDescriptors(for identifier: CharacteristicIdentifier) -> + Observable<[Descriptor]> { + return characteristic(with: identifier) + .flatMap { [weak self] in + self?.discoverDescriptors(for: $0) ?? .error(BluetoothError.destroyed) + } + } + + /// Function that allow to monitor writes that happened for descriptor. + /// - parameter identifier: unique identifier of descriptor, which also holds information about characteristic that descriptor belongs to. + /// - Returns: Observable that emits `Next` with `Descriptor` instance every time when write has happened. + /// It's **infinite** stream, so `.Complete` is never called. + public func monitorWrite(for identifier: DescriptorIdentifier) -> Observable { + return descriptor(with: identifier) + .flatMap { [weak self] in + self?.monitorWrite(for: $0) ?? .error(BluetoothError.destroyed) + } + } + + /// Function that triggers write of data to descriptor. Write is called after subscribtion to `Observable` is made. + /// - Parameter data: `Data` that'll be written to `Descriptor` instance + /// - parameter identifier: unique identifier of descriptor, which also holds information about characteristic that descriptor belongs to. + /// - Returns: Observable that emits `Next` with `Descriptor` instance, once value is written successfully. + /// Immediately after that `.Complete` is emitted. + public func writeValue(_ data: Data, for identifier: DescriptorIdentifier) + -> Observable { + return descriptor(with: identifier) + .flatMap { [weak self] in + self?.writeValue(data, for: $0) ?? .error(BluetoothError.destroyed) + } + } + + /// Function that allow to monitor value updates for `Descriptor` instance. + /// - parameter identifier: unique identifier of descriptor, which also holds information about characteristic that descriptor belongs to. + /// - Returns: Observable that emits `Next` with `Descriptor` instance every time when value has changed. + /// It's **infinite** stream, so `.Complete` is never called. + public func monitorValueUpdate(for identifier: DescriptorIdentifier) -> Observable { + return descriptor(with: identifier) + .flatMap { [weak self] in + self?.monitorValueUpdate(for: $0) ?? .error(BluetoothError.destroyed) + } + } + + /// Function that triggers read of current value of the `Descriptor` instance. + /// Read is called after subscription to `Observable` is made. + /// - Parameter descriptor: `Descriptor` to read value from + /// - Returns: Observable which emits `Next` with given descriptor when value is ready to read. Immediately after that `.Complete` is emitted. + public func readValue(for identifier: DescriptorIdentifier) -> Observable { + return descriptor(with: identifier) + .flatMap { [weak self] in + self?.readValue(for: $0) ?? .error(BluetoothError.destroyed) + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Peripheral.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Peripheral.swift new file mode 100644 index 000000000..c61b475ea --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Peripheral.swift @@ -0,0 +1,516 @@ +import Foundation +import CoreBluetooth + +// swiftlint:disable line_length + +/// Peripheral is a class implementing ReactiveX API which wraps all Core Bluetooth functions +/// allowing to talk to peripheral like discovering characteristics, services and all of the read/write calls. +public class Peripheral { + public let manager: BluetoothManager + + init(manager: BluetoothManager, peripheral: RxPeripheralType) { + self.manager = manager + self.peripheral = peripheral + } + + /// Implementation of peripheral + let peripheral: RxPeripheralType + + /// Continuous value indicating if peripheral is in connected state. This is continuous value, which first emits `.Next` with current state, and later whenever state change occurs + public var rx_isConnected: Observable { + return .deferred { + let disconnected = self.manager.monitorDisconnection(for: self).map { _ in false } + let connected = self.manager.monitorConnection(for: self).map { _ in true } + return Observable.of(disconnected, connected).merge().startWith(self.isConnected) + } + } + + /// Value indicating if peripheral is currently in connected state. + public var isConnected: Bool { + return peripheral.state == .connected + } + + /// Underlying `CBPeripheral` instance + public var cbPeripheral: CBPeripheral { + return peripheral.peripheral + } + + /// Current state of `Peripheral` instance described by [CBPeripheralState](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBPeripheral_Class/#//apple_ref/c/tdef/CBPeripheralState). + /// - returns: Current state of `Peripheral` as `CBPeripheralState`. + public var state: CBPeripheralState { + return peripheral.state + } + + /// Current name of `Peripheral` instance. Analogous to [name](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBPeripheral_Class/#//apple_ref/c/tdef/name) of `CBPeripheral`. + public var name: String? { + return peripheral.name + } + + /// Unique identifier of `Peripheral` instance. Assigned once peripheral is discovered by the system. + + public var identifier: UUID { + return peripheral.identifier + } + + /// Unique identifier of `Peripheral` object instance. Should be removed in 4.0 + @available(*, deprecated) + public var objectId: UInt { + return peripheral.objectId + } + + /// A list of services that have been discovered. Analogous to [services](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBPeripheral_Class/#//apple_ref/occ/instp/CBPeripheral/services) of `CBPeripheral`. + public var services: [Service]? { + return peripheral.services?.map { + Service(peripheral: self, service: $0) + } + } + + /// Establishes local connection to the peripheral. + /// For more information look into `BluetoothManager.connectToPeripheral(_:options:)` because this method calls it directly. + /// - Parameter peripheral: The `Peripheral` to which `BluetoothManager` is attempting to connect. + /// - Parameter options: Dictionary to customise the behaviour of connection. + /// - Returns: Observation which emits next event after connection is established + public func connect(options: [String: AnyObject]? = nil) -> Observable { + return manager.connect(self, options: options) + } + + /// Cancels an active or pending local connection to a `Peripheral` after observable subscription. It is not guaranteed + /// that physical connection will be closed immediately as well and all pending commands will not be executed. + /// - returns: Observable which emits next and complete events when peripheral successfully cancelled connection. + public func cancelConnection() -> Observable { + return manager.cancelPeripheralConnection(self) + } + + /// Triggers discover of specified services of peripheral. If the servicesUUIDs parameter is nil, all the available services of the + /// peripheral are returned; setting the parameter to nil is considerably slower and is not recommended. + /// If all of the specified services are already discovered - these are returned without doing any underlying Bluetooth operations. + /// Next on returned `Observable` is emitted only when all of the requested services are discovered. + /// - Parameter serviceUUIDs: An array of [CBUUID](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBUUID_Class/) objects that you are interested in. Here, each [CBUUID](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBUUID_Class/) object represents a UUID that identifies the type of service you want to discover. + /// - Returns: Observable that emits `Next` with array of `Service` instances, once they're discovered. + /// Immediately after that `.Complete` is emitted. + public func discoverServices(_ serviceUUIDs: [CBUUID]?) -> Observable<[Service]> { + if let identifiers = serviceUUIDs, !identifiers.isEmpty, + let cachedServices = self.services, + let filteredServices = filterUUIDItems(uuids: serviceUUIDs, items: cachedServices) { + return ensureValidPeripheralState(for: .just(filteredServices)) + } + let observable = peripheral.rx_didDiscoverServices + .flatMap { [weak self] (_, error) -> Observable<[Service]> in + guard let strongSelf = self else { throw BluetoothError.destroyed } + guard let cachedServices = strongSelf.services, error == nil else { + throw BluetoothError.servicesDiscoveryFailed(strongSelf, error) + } + if let filteredServices = filterUUIDItems(uuids: serviceUUIDs, items: cachedServices) { + return .just(filteredServices) + } + return .empty() + } + .take(1) + + return ensureValidPeripheralStateAndCallIfSucceeded( + for: observable, + postSubscriptionCall: { [weak self] in self?.peripheral.discoverServices(serviceUUIDs) } + ) + } + + /// Function that triggers included services discovery for specified services. Discovery is called after + /// subscribtion to `Observable` is made. + /// If all of the specified included services are already discovered - these are returned without doing any underlying Bluetooth operations. + /// Next on returned `Observable` is emitted only when all of the requested included services are discovered. + /// - Parameter includedServiceUUIDs: Identifiers of included services that should be discovered. If `nil` - all of the + /// included services will be discovered. If you'll pass empty array - none of them will be discovered. + /// - Parameter forService: Service of which included services should be discovered. + /// - Returns: Observable that emits `Next` with array of `Service` instances, once they're discovered. + /// Immediately after that `.Complete` is emitted. + public func discoverIncludedServices(_ includedServiceUUIDs: [CBUUID]?, for service: Service) -> Observable<[Service]> { + if let identifiers = includedServiceUUIDs, !identifiers.isEmpty, + let services = service.includedServices, + let filteredServices = filterUUIDItems(uuids: includedServiceUUIDs, items: services) { + return ensureValidPeripheralState(for: .just(filteredServices)) + } + let observable = peripheral + .rx_didDiscoverIncludedServicesForService + .filter { $0.0 == service.service } + .flatMap { [weak self] (rxservice, error) -> Observable<[Service]> in + guard let strongSelf = self else { throw BluetoothError.destroyed } + guard let includedRxServices = rxservice.includedServices, error == nil else { + throw BluetoothError.includedServicesDiscoveryFailed(strongSelf, error) + } + let includedServices = includedRxServices.map { Service(peripheral: strongSelf, service: $0) } + if let filteredServices = filterUUIDItems(uuids: includedServiceUUIDs, items: includedServices) { + return .just(filteredServices) + } + return .empty() + } + .take(1) + + return ensureValidPeripheralStateAndCallIfSucceeded( + for: observable, + postSubscriptionCall: { [weak self] in + self?.peripheral.discoverIncludedServices(includedServiceUUIDs, for: service.service) + } + ) + } + + // MARK: Characteristics + /// Function that triggers characteristics discovery for specified Services and identifiers. Discovery is called after + /// subscribtion to `Observable` is made. + /// If all of the specified characteristics are already discovered - these are returned without doing any underlying Bluetooth operations. + /// Next on returned `Observable` is emitted only when all of the requested characteristics are discovered. + /// - Parameter characteristicUUIDs: Identifiers of characteristics that should be discovered. If `nil` - all of the + /// characteristics will be discovered. If you'll pass empty array - none of them will be discovered. + /// - Parameter service: Service of which characteristics should be discovered. + /// Immediately after that `.Complete` is emitted. + public func discoverCharacteristics(_ characteristicUUIDs: [CBUUID]?, for service: Service) -> Observable<[Characteristic]> { + if let identifiers = characteristicUUIDs, !identifiers.isEmpty, + let characteristics = service.characteristics, + let filteredCharacteristics = filterUUIDItems(uuids: characteristicUUIDs, items: characteristics) { + return ensureValidPeripheralState(for: .just(filteredCharacteristics)) + } + let observable = peripheral + .rx_didDiscoverCharacteristicsForService + .filter { $0.0 == service.service } + .flatMap { (cbService, error) -> Observable<[Characteristic]> in + guard let rxCharacteristics = cbService.characteristics, error == nil else { + throw BluetoothError.characteristicsDiscoveryFailed(service, error) + } + let characteristics = rxCharacteristics.map { Characteristic(characteristic: $0, service: service) } + if let filteredCharacteristics = filterUUIDItems(uuids: characteristicUUIDs, items: characteristics) { + return .just(filteredCharacteristics) + } + return .empty() + } + .take(1) + + return ensureValidPeripheralStateAndCallIfSucceeded( + for: observable, + postSubscriptionCall: { [weak self] in + self?.peripheral.discoverCharacteristics(characteristicUUIDs, for: service.service) } + ) + } + + /// Function that allow to monitor writes that happened for characteristic. + /// - Parameter characteristic: Characteristic of which value writes should be monitored. + /// - Returns: Observable that emits `Next` with `Characteristic` instance every time when write has happened. + /// It's **infinite** stream, so `.Complete` is never called. + public func monitorWrite(for characteristic: Characteristic) -> Observable { + let observable = peripheral + .rx_didWriteValueForCharacteristic + .filter { return $0.0 == characteristic.characteristic } + .map { (_, error) -> Characteristic in + if let error = error { + throw BluetoothError.characteristicWriteFailed(characteristic, error) + } + return characteristic + } + return ensureValidPeripheralState(for: observable) + } + + /// @method maximumWriteValueLengthForType: + /// @discussion The maximum amount of data, in bytes, that can be sent to a characteristic in a single write type. + /// @see writeValue:forCharacteristic:type: + @available(OSX 10.12, iOS 9.0, *) + public func maximumWriteValueLength(for type: CBCharacteristicWriteType) -> Int { + return peripheral.maximumWriteValueLength(for: type) + } + + /// Function that triggers write of data to characteristic. Write is called after subscribtion to `Observable` is made. + /// Behavior of this function strongly depends on [CBCharacteristicWriteType](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBPeripheral_Class/#//apple_ref/swift/enum/c:@E@CBCharacteristicWriteType), so be sure to check this out before usage of the method. + /// - parameter data: Data that'll be written written to `Characteristic` instance + /// - parameter forCharacteristic: `Characteristic` instance to write value to. + /// - parameter type: Type of write operation. Possible values: `.WithResponse`, `.WithoutResponse` + /// - returns: Observable that emition depends on `CBCharacteristicWriteType` passed to the function call. + /// Behavior is following: + /// - `withResponse` - Observable emits `Next` with `Characteristic` instance write was confirmed without any errors. + /// Immediately after that `Complete` is called. If any problem has happened, errors are emitted. + /// - `withoutResponse` - Observable emits `Next` with `Characteristic` instance once write was called. + /// Immediately after that `.Complete` is called. Result of this call is not checked, so as a user you are not sure if everything completed successfully. Errors are not emitted + public func writeValue(_ data: Data, + for characteristic: Characteristic, + type: CBCharacteristicWriteType) -> Observable { + let observable: Observable + switch type { + case .withoutResponse: + observable = self.peripheral + .rx_isReadyToSendWriteWithoutResponse + .startWith(peripheral.canSendWriteWithoutResponse) + .filter { $0 } + .take(1) + .map { [weak self] _ in + self?.peripheral.writeValue(data, for: characteristic.characteristic, type: type) + return characteristic + } + + case .withResponse: + let action = Observable.deferred { [weak self] in + self?.peripheral.writeValue(data, for: characteristic.characteristic, type: type) + return .empty() + } + + let monitor = peripheral + .rx_didWriteValueForCharacteristic + .filter { return $0.0 == characteristic.characteristic } + .take(1) + .map { (_, error) -> Characteristic in + if let error = error { + throw BluetoothError.characteristicWriteFailed(characteristic, error) + } + return characteristic + } + + observable = Observable.merge([monitor, action]) + } + return ensureValidPeripheralState(for: observable) + } + + /// Function that allow to monitor value updates for `Characteristic` instance. + /// - Parameter characteristic: Characteristic of which value changes should be monitored. + /// - Returns: Observable that emits `Next` with `Characteristic` instance every time when value has changed. + /// It's **infinite** stream, so `.Complete` is never called. + public func monitorValueUpdate(for characteristic: Characteristic) -> Observable { + let observable = peripheral + .rx_didUpdateValueForCharacteristic + .filter { $0.0 == characteristic.characteristic } + .map { (_, error) -> Characteristic in + if let error = error { + throw BluetoothError.characteristicReadFailed(characteristic, error) + } + return characteristic + } + return ensureValidPeripheralState(for: observable) + } + + /// Function that triggers read of current value of the `Characteristic` instance. + /// Read is called after subscription to `Observable` is made. + /// - Parameter characteristic: `Characteristic` to read value from + /// - Returns: Observable which emits `Next` with given characteristic when value is ready to read. Immediately after that `.Complete` is emitted. + public func readValue(for characteristic: Characteristic) -> Observable { + let observable = monitorValueUpdate(for: characteristic).take(1) + return ensureValidPeripheralStateAndCallIfSucceeded( + for: observable, + postSubscriptionCall: { [weak self] in + self?.peripheral.readValue(for: characteristic.characteristic) + } + ) + } + + /// Function that triggers set of notification state of the `Characteristic`. + /// This change is called after subscribtion to `Observable` is made. + /// - warning: This method is not responsible for emitting values every time that `Characteristic` value is changed. + /// For this, refer to other method: `monitorValueUpdateForCharacteristic(_)`. These two are often called together. + /// - parameter enabled: New value of notifications state. Specify `true` if you're interested in getting values + /// - parameter forCharacteristic: Characterististic of which notification state needs to be changed + /// - returns: Observable which emits `Next` with Characteristic that state was changed. Immediately after `.Complete` is emitted + public func setNotifyValue(_ enabled: Bool, + for characteristic: Characteristic) -> Observable { + let observable = peripheral + .rx_didUpdateNotificationStateForCharacteristic + .filter { $0.0 == characteristic.characteristic } + .take(1) + .map { (_, error) -> Characteristic in + if let error = error { + throw BluetoothError.characteristicNotifyChangeFailed(characteristic, error) + } + return characteristic + } + return ensureValidPeripheralStateAndCallIfSucceeded( + for: observable, + postSubscriptionCall: { [weak self] in + self?.peripheral.setNotifyValue(enabled, for: characteristic.characteristic) + } + ) + } + + /// Function that triggers set of notification state of the `Characteristic`, and monitor for any incoming updates. + /// Notification is set after subscribtion to `Observable` is made. + /// - parameter characteristic: Characterististic on which notification should be made. + /// - returns: Observable which emits `Next`, when characteristic value is updated. + /// This is **infinite** stream of values. + public func setNotificationAndMonitorUpdates(for characteristic: Characteristic) + -> Observable { + return Observable + .of( + monitorValueUpdate(for: characteristic), + setNotifyValue(true, for: characteristic) + .ignoreElements() + .asObservable() + .map { _ in characteristic } + .subscribeOn(CurrentThreadScheduler.instance) + ) + .merge() + } + + // MARK: Descriptors + /// Function that triggers descriptors discovery for characteristic + /// If all of the descriptors are already discovered - these are returned without doing any underlying Bluetooth operations. + /// - Parameter characteristic: `Characteristic` instance for which descriptors should be discovered. + /// - Returns: Observable that emits `Next` with array of `Descriptor` instances, once they're discovered. + /// Immediately after that `.Complete` is emitted. + public func discoverDescriptors(for characteristic: Characteristic) -> Observable<[Descriptor]> { + if let descriptors = characteristic.descriptors { + let resultDescriptors = descriptors.map { Descriptor(descriptor: $0.descriptor, characteristic: characteristic) } + return ensureValidPeripheralState(for: .just(resultDescriptors)) + } + let observable = peripheral + .rx_didDiscoverDescriptorsForCharacteristic + .filter { $0.0 == characteristic.characteristic } + .take(1) + .map { (cbCharacteristic, error) -> [Descriptor] in + if let descriptors = cbCharacteristic.descriptors, error == nil { + return descriptors.map { + Descriptor(descriptor: $0, characteristic: characteristic) } + } + throw BluetoothError.descriptorsDiscoveryFailed(characteristic, error) + } + + return ensureValidPeripheralStateAndCallIfSucceeded( + for: observable, + postSubscriptionCall: { [weak self] in + self?.peripheral.discoverDescriptors(for: characteristic.characteristic) } + ) + } + + /// Function that allow to monitor writes that happened for descriptor. + /// - Parameter descriptor: Descriptor of which value writes should be monitored. + /// - Returns: Observable that emits `Next` with `Descriptor` instance every time when write has happened. + /// It's **infinite** stream, so `.Complete` is never called. + public func monitorWrite(for descriptor: Descriptor) -> Observable { + let observable = peripheral + .rx_didWriteValueForDescriptor + .filter { $0.0 == descriptor.descriptor } + .map { (_, error) -> Descriptor in + if let error = error { + throw BluetoothError.descriptorWriteFailed(descriptor, error) + } + return descriptor + } + return ensureValidPeripheralState(for: observable) + } + + /// Function that allow to monitor value updates for `Descriptor` instance. + /// - Parameter descriptor: Descriptor of which value changes should be monitored. + /// - Returns: Observable that emits `Next` with `Descriptor` instance every time when value has changed. + /// It's **infinite** stream, so `.Complete` is never called. + public func monitorValueUpdate(for descriptor: Descriptor) -> Observable { + let observable = peripheral.rx_didUpdateValueForDescriptor + .filter { $0.0 == descriptor.descriptor } + .map { (_, error) -> Descriptor in + if let error = error { + throw BluetoothError.descriptorReadFailed(descriptor, error) + } + return descriptor + } + return ensureValidPeripheralState(for: observable) + } + + /// Function that triggers read of current value of the `Descriptor` instance. + /// Read is called after subscription to `Observable` is made. + /// - Parameter descriptor: `Descriptor` to read value from + /// - Returns: Observable which emits `Next` with given descriptor when value is ready to read. Immediately after that + /// `.Complete` is emitted. + public func readValue(for descriptor: Descriptor) -> Observable { + let observable = monitorValueUpdate(for: descriptor).take(1) + return ensureValidPeripheralStateAndCallIfSucceeded( + for: observable, + postSubscriptionCall: { [weak self] in + self?.peripheral.readValue(for: descriptor.descriptor) } + ) + } + + /// Function that triggers write of data to descriptor. Write is called after subscribtion to `Observable` is made. + /// - Parameter data: `Data` that'll be written to `Descriptor` instance + /// - Parameter descriptor: `Descriptor` instance to write value to. + /// - Returns: Observable that emits `Next` with `Descriptor` instance, once value is written successfully. + /// Immediately after that `.Complete` is emitted. + public func writeValue(_ data: Data, for descriptor: Descriptor) -> Observable { + let monitorWrite = self.monitorWrite(for: descriptor).take(1) + return ensureValidPeripheralStateAndCallIfSucceeded( + for: monitorWrite, + postSubscriptionCall: { [weak self] in + self?.peripheral.writeValue(data, for: descriptor.descriptor) } + ) + } + + func ensureValidPeripheralStateAndCallIfSucceeded(for observable: Observable, + postSubscriptionCall call: @escaping () -> Void + ) -> Observable { + let operation = Observable.deferred { + call() + return .empty() + } + return ensureValidPeripheralState(for: Observable.merge([observable, operation])) + } + + /// Function that merges given observable with error streams of invalid Central Manager states. + /// - parameter observable: observation to be transformed + /// - returns: Source observable which listens on state chnage errors as well + func ensureValidPeripheralState(for observable: Observable) -> Observable { + return Observable.absorb( + manager.ensurePeripheralIsConnected(self), + manager.ensure(.poweredOn, observable: observable) + ) + } + + /// Function that triggers read of `Peripheral` RSSI value. Read is called after subscription to `Observable` is made. + /// - returns: Observable that emits tuple: `(Peripheral, Int)` once new RSSI value is read, and just after that + /// `.Complete` event. `Int` is new RSSI value, `Peripheral` is returned to allow easier chaining. + public func readRSSI() -> Observable<(Peripheral, Int)> { + let observable = peripheral.rx_didReadRSSI + .take(1) + .map { [weak self] (rssi, error) -> (Peripheral, Int) in + guard let strongSelf = self else { throw BluetoothError.destroyed } + if let error = error { + throw BluetoothError.peripheralRSSIReadFailed(strongSelf, error) + } + return (strongSelf, rssi) + } + + return ensureValidPeripheralStateAndCallIfSucceeded( + for: observable, + postSubscriptionCall: { [weak self] in + self?.peripheral.readRSSI() } + ) + } + + /// Function that allow user to monitor incoming `name` property changes of `Peripheral` instance. + /// - returns: Observable that emits tuples: `(Peripheral, String?)` when name has changed. + /// It's `optional String` because peripheral could also lost his name. + /// It's **infinite** stream of values, so `.Complete` is never emitted. + public func monitorNameUpdate() -> Observable<(Peripheral, String?)> { + let observable = peripheral.rx_didUpdateName.map { [weak self] name -> (Peripheral, String?) in + guard let strongSelf = self else { throw BluetoothError.destroyed } + return (strongSelf, name) + } + return ensureValidPeripheralState(for: observable) + } + + /// Function that allow to monitor incoming service modifications for `Peripheral` instance. + /// In case you're interested what exact changes might occur - please refer to + /// [Apple Documentation](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBPeripheralDelegate_Protocol/#//apple_ref/occ/intfm/CBPeripheralDelegate/peripheral:didModifyServices:) + /// - returns: Observable that emits tuples: `(Peripheral, [Service])` when services were modified. + /// It's **infinite** stream of values, so `.Complete` is never emitted. + public func monitorServicesModification() -> Observable<(Peripheral, [Service])> { + let observable = peripheral.rx_didModifyServices + .map { [weak self] services -> [Service] in + guard let strongSelf = self else { throw BluetoothError.destroyed } + return services.map { Service(peripheral: strongSelf, service: $0) } } + .map { [weak self] services -> (Peripheral, [Service]) in + guard let strongSelf = self else { throw BluetoothError.destroyed } + return (strongSelf, services) + } + return ensureValidPeripheralState(for: observable) + } +} + +extension Peripheral: Equatable {} + +/** + Compare two peripherals which are the same when theirs identifiers are equal. + + - parameter lhs: First peripheral to compare + - parameter rhs: Second peripheral to compare + - returns: True if both peripherals are the same + */ +public func == (lhs: Peripheral, rhs: Peripheral) -> Bool { + return lhs.peripheral == rhs.peripheral +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RestoredState.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RestoredState.swift new file mode 100644 index 000000000..64e2679aa --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RestoredState.swift @@ -0,0 +1,59 @@ +import Foundation +import CoreBluetooth + +#if os(iOS) + /// Convenience class which helps reading state of restored BluetoothManager. + public struct RestoredState { + + /// Restored state dictionary. + public let restoredStateData: [String: Any] + + public unowned let bluetoothManager: BluetoothManager + /// Creates restored state information based on CoreBluetooth's dictionary + /// - parameter restoredStateDictionary: Core Bluetooth's restored state data + /// - parameter bluetoothManager: `BluetoothManager` instance of which state has been restored. + init(restoredStateDictionary: [String: Any], bluetoothManager: BluetoothManager) { + restoredStateData = restoredStateDictionary + self.bluetoothManager = bluetoothManager + } + + /// Array of `Peripheral` objects which have been restored. + /// These are peripherals that were connected to the central manager (or had a connection pending) + /// at the time the app was terminated by the system. + public var peripherals: [Peripheral] { + let objects = restoredStateData[CBCentralManagerRestoredStatePeripheralsKey] as? [AnyObject] + guard let arrayOfAnyObjects = objects else { return [] } + return arrayOfAnyObjects.compactMap { $0 as? CBPeripheral } + .map(RxCBPeripheral.init) + .map { Peripheral(manager: bluetoothManager, peripheral: $0) } + } + + /// Dictionary that contains all of the peripheral scan options that were being used + /// by the central manager at the time the app was terminated by the system. + public var scanOptions: [String: AnyObject]? { + return restoredStateData[CBCentralManagerRestoredStatePeripheralsKey] as? [String: AnyObject] + } + + /// Array of `Service` objects which have been restored. + /// These are all the services the central manager was scanning for at the time the app + /// was terminated by the system. + public var services: [Service] { + let objects = restoredStateData[CBCentralManagerRestoredStateScanServicesKey] as? [AnyObject] + guard let arrayOfAnyObjects = objects else { return [] } + return arrayOfAnyObjects.compactMap { $0 as? CBService } + .map(RxCBService.init) + .compactMap { + + // Necessary to accomodate the changes between + // iOS 14 and iOS 15 + let optPeripheral: CBPeripheral? = $0.service.peripheral + guard let peripheral = optPeripheral else { + return nil + } + + return Service(peripheral: Peripheral(manager: bluetoothManager, + peripheral: RxCBPeripheral(peripheral: peripheral)), + service: $0) } + } + } +#endif diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxBluetoothKit.h b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxBluetoothKit.h new file mode 100644 index 000000000..43aab58d0 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxBluetoothKit.h @@ -0,0 +1,12 @@ +#import + +//! Project version number for RxBluetoothKit. +FOUNDATION_EXPORT double RxBluetoothKitVersionNumber; + +//! Project version string for RxBluetoothKit. +FOUNDATION_EXPORT const unsigned char RxBluetoothKitVersionString[]; + +// In this header, you should import all the public headers of your framework using +// statements like #import + + diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBCentralManager.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBCentralManager.swift new file mode 100644 index 000000000..9e8f5f19b --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBCentralManager.swift @@ -0,0 +1,149 @@ +import Foundation +import CoreBluetooth + +class RxCBCentralManager: RxCentralManagerType { + + let centralManager: CBCentralManager + private let internalDelegate = InternalDelegate() + + @available(*, deprecated) + var objectId: UInt { + return UInt(bitPattern: ObjectIdentifier(centralManager)) + } + + init(queue: DispatchQueue, options: [String: AnyObject]? = nil) { + centralManager = CBCentralManager(delegate: internalDelegate, queue: queue, options: options) + } + + @objc private class InternalDelegate: NSObject, CBCentralManagerDelegate { + let didUpdateStateSubject = PublishSubject() + let willRestoreStateSubject = ReplaySubject<[String: Any]>.create(bufferSize: 1) + let didDiscoverPeripheralSubject = PublishSubject<(RxPeripheralType, [String: Any], NSNumber)>() + let didConnectPerihperalSubject = PublishSubject() + let didFailToConnectPeripheralSubject = PublishSubject<(RxPeripheralType, Error?)>() + let didDisconnectPeripheral = PublishSubject<(RxPeripheralType, Error?)>() + + @objc func centralManagerDidUpdateState(_ central: CBCentralManager) { + guard let bleState = BluetoothState(rawValue: central.state.rawValue) else { return } + RxBluetoothKitLog.d("\(central.logDescription) didUpdateState(state: \(bleState.logDescription))") + didUpdateStateSubject.onNext(bleState) + } + + @objc func centralManager(_ central: CBCentralManager, willRestoreState dict: [String: Any]) { + RxBluetoothKitLog.d("\(central.logDescription) willRestoreState(restoredState: \(dict))") + willRestoreStateSubject.onNext(dict) + } + + @objc func centralManager(_ central: CBCentralManager, + didDiscover peripheral: CBPeripheral, + advertisementData: [String: Any], + rssi: NSNumber) { + RxBluetoothKitLog.v(""" + \(central.logDescription) didDiscover(peripheral: \(peripheral.logDescription), + rssi: \(rssi)) + """) + didDiscoverPeripheralSubject.onNext((RxCBPeripheral(peripheral: peripheral), advertisementData, rssi)) + } + + @objc func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { + didConnectPerihperalSubject.onNext(RxCBPeripheral(peripheral: peripheral)) + } + + @objc func centralManager(_ central: CBCentralManager, + didFailToConnect peripheral: CBPeripheral, + error: Error?) { + RxBluetoothKitLog.d(""" + \(central.logDescription) didFailToConnect(to: \(peripheral.logDescription), + error: \(String(describing: error))) + """) + didFailToConnectPeripheralSubject.onNext((RxCBPeripheral(peripheral: peripheral), error)) + } + + @objc func centralManager(_ central: CBCentralManager, + didDisconnectPeripheral peripheral: CBPeripheral, + error: Error?) { + RxBluetoothKitLog.d(""" + \(central.logDescription) didDisconnect(from: \(peripheral.logDescription), + error: \(String(describing: error))) + """) + didDisconnectPeripheral.onNext((RxCBPeripheral(peripheral: peripheral), error)) + } + } + + var rx_didUpdateState: Observable { + return internalDelegate.didUpdateStateSubject + } + + var rx_willRestoreState: Observable<[String: Any]> { + return internalDelegate.willRestoreStateSubject + } + + var rx_didDiscoverPeripheral: Observable<(RxPeripheralType, [String: Any], NSNumber)> { + return internalDelegate.didDiscoverPeripheralSubject + } + + var rx_didConnectPeripheral: Observable { + return internalDelegate.didConnectPerihperalSubject + } + + var rx_didFailToConnectPeripheral: Observable<(RxPeripheralType, Error?)> { + return internalDelegate.didFailToConnectPeripheralSubject + } + + var rx_didDisconnectPeripheral: Observable<(RxPeripheralType, Error?)> { + return internalDelegate.didDisconnectPeripheral + } + + var state: BluetoothState { + return BluetoothState(rawValue: centralManager.state.rawValue) ?? .unsupported + } + + func scanForPeripherals(withServices serviceUUIDs: [CBUUID]?, options: [String: Any]?) { + RxBluetoothKitLog.d(""" + \(centralManager.logDescription) scanForPeripherals( + withServices: \(String(describing: serviceUUIDs?.logDescription)), + options: \(String(describing: options))) + """) + return centralManager.scanForPeripherals(withServices: serviceUUIDs, options: options) + } + + func connect(_ peripheral: RxPeripheralType, options: [String: Any]?) { + let cbperipheral = (peripheral as! RxCBPeripheral).peripheral + RxBluetoothKitLog.d(""" + \(centralManager.logDescription) connect( + peripheral: \(cbperipheral.logDescription), + options: \(String(describing: options))) + """) + return centralManager.connect(cbperipheral, options: options) + } + + func cancelPeripheralConnection(_ peripheral: RxPeripheralType) { + let cbperipheral = (peripheral as! RxCBPeripheral).peripheral + RxBluetoothKitLog.d(""" + \(centralManager.logDescription) cancelPeripheralConnection( + peripheral: \(cbperipheral.logDescription)) + """) + return centralManager.cancelPeripheralConnection(cbperipheral) + } + + func stopScan() { + RxBluetoothKitLog.d("\(centralManager.logDescription) stopScan()") + return centralManager.stopScan() + } + + func retrieveConnectedPeripherals(withServices serviceUUIDs: [CBUUID]) -> Observable<[RxPeripheralType]> { + RxBluetoothKitLog.d(""" + \(centralManager.logDescription) retrieveConnectedPeripherals( + withServices: \(serviceUUIDs.logDescription)) + """) + return .just(centralManager.retrieveConnectedPeripherals(withServices: serviceUUIDs).map(RxCBPeripheral.init)) + } + + func retrievePeripherals(withIdentifiers identifiers: [UUID]) -> Observable<[RxPeripheralType]> { + RxBluetoothKitLog.d(""" + \(centralManager.logDescription) retrievePeripherals( + withIdentifiers: \(identifiers.logDescription)) + """) + return .just(centralManager.retrievePeripherals(withIdentifiers: identifiers).map(RxCBPeripheral.init)) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBCharacteristic.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBCharacteristic.swift new file mode 100644 index 000000000..667491e0d --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBCharacteristic.swift @@ -0,0 +1,51 @@ +import Foundation +import CoreBluetooth + +class RxCBCharacteristic: RxCharacteristicType { + + let characteristic: CBCharacteristic + + init(characteristic: CBCharacteristic) { + self.characteristic = characteristic + } + + init?(characteristic: CBCharacteristic?) { + guard let characteristic = characteristic else { + return nil + } + self.characteristic = characteristic + } + + var objectId: UInt { + return UInt(bitPattern: ObjectIdentifier(characteristic)) + } + + var uuid: CBUUID { + return characteristic.uuid + } + + var value: Data? { + return characteristic.value + } + + var isNotifying: Bool { + return characteristic.isNotifying + } + + var properties: CBCharacteristicProperties { + return characteristic.properties + } + + var descriptors: [RxDescriptorType]? { + return characteristic.descriptors?.map(RxCBDescriptor.init) + } + + var service: RxServiceType? { + return RxCBService(service: characteristic.service) + } + + func isEqualTo(characteristic: RxCharacteristicType) -> Bool { + guard let rhs = characteristic as? RxCBCharacteristic else { return false } + return self.characteristic === rhs.characteristic + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBDescriptor.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBDescriptor.swift new file mode 100644 index 000000000..803b58d72 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBDescriptor.swift @@ -0,0 +1,32 @@ +import Foundation +import CoreBluetooth + +class RxCBDescriptor: RxDescriptorType { + + let descriptor: CBDescriptor + + init(descriptor: CBDescriptor) { + self.descriptor = descriptor + } + + var objectId: UInt { + return UInt(bitPattern: ObjectIdentifier(descriptor)) + } + + var uuid: CBUUID { + return descriptor.uuid + } + + var characteristic: RxCharacteristicType? { + return RxCBCharacteristic(characteristic: descriptor.characteristic) + } + + var value: Any? { + return descriptor.value + } + + func isEqualTo(descriptor: RxDescriptorType) -> Bool { + guard let rhs = descriptor as? RxCBDescriptor else { return false } + return self.descriptor === rhs.descriptor + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBPeripheral.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBPeripheral.swift new file mode 100644 index 000000000..9547b1e6f --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBPeripheral.swift @@ -0,0 +1,394 @@ +import Foundation +import CoreBluetooth + +class RxCBPeripheral: RxPeripheralType { + + let peripheral: CBPeripheral + private let internalDelegate: InternalPeripheralDelegate + + init(peripheral: CBPeripheral) { + self.peripheral = peripheral + internalDelegate = RxCBPeripheral.getInternalPeripheralDelegateRef(cbPeripheral: peripheral) + } + + deinit { + RxCBPeripheral.putInternalPeripheralDelegateRef(cbPeripheral: peripheral) + } + + var identifier: UUID { + return peripheral.value(forKey: "identifier") as! NSUUID as UUID + } + + var objectId: UInt { + return UInt(bitPattern: ObjectIdentifier(peripheral)) + } + + var name: String? { + return peripheral.name + } + + var state: CBPeripheralState { + return peripheral.state + } + + var services: [RxServiceType]? { + return peripheral.services?.compactMap(RxCBService.init) + } + + var canSendWriteWithoutResponse: Bool { + // Although available since iOS 11.0, on versions < iOS 11.2 canSendWriteWithoutResponse will always + // return false (on first try). We work around this issue by always returning true for < iOS 11.2. + // See: https://github.com/Polidea/react-native-ble-plx/issues/365 + if #available(iOS 11.2, *) { + return peripheral.canSendWriteWithoutResponse + } else { + return true + } + } + + var rx_didUpdateName: Observable { + return internalDelegate.peripheralDidUpdateNameSubject + } + + var rx_didModifyServices: Observable<([RxServiceType])> { + return internalDelegate.peripheralDidModifyServicesSubject + } + + var rx_didReadRSSI: Observable<(Int, Error?)> { + return internalDelegate.peripheralDidReadRSSISubject + } + + var rx_didDiscoverServices: Observable<([RxServiceType]?, Error?)> { + return internalDelegate.peripheralDidDiscoverServicesSubject + } + + var rx_didDiscoverIncludedServicesForService: Observable<(RxServiceType, Error?)> { + return internalDelegate.peripheralDidDiscoverIncludedServicesForServiceSubject + } + + var rx_didDiscoverCharacteristicsForService: Observable<(RxServiceType, Error?)> { + return internalDelegate.peripheralDidDiscoverCharacteristicsForServiceSubject + } + + var rx_didUpdateValueForCharacteristic: Observable<(RxCharacteristicType, Error?)> { + return internalDelegate.peripheralDidUpdateValueForCharacteristicSubject + } + + var rx_didWriteValueForCharacteristic: Observable<(RxCharacteristicType, Error?)> { + return internalDelegate.peripheralDidWriteValueForCharacteristicSubject + } + + var rx_didUpdateNotificationStateForCharacteristic: Observable<(RxCharacteristicType, Error?)> { + return internalDelegate.peripheralDidUpdateNotificationStateForCharacteristicSubject + } + + var rx_didDiscoverDescriptorsForCharacteristic: Observable<(RxCharacteristicType, Error?)> { + return internalDelegate.peripheralDidDiscoverDescriptorsForCharacteristicSubject + } + + var rx_didUpdateValueForDescriptor: Observable<(RxDescriptorType, Error?)> { + return internalDelegate.peripheralDidUpdateValueForDescriptorSubject + } + + var rx_didWriteValueForDescriptor: Observable<(RxDescriptorType, Error?)> { + return internalDelegate.peripheralDidWriteValueForDescriptorSubject + } + + var rx_isReadyToSendWriteWithoutResponse: Observable { + return internalDelegate.peripheralIsReadyToSendWriteWithoutResponseSubject + } + + func discoverServices(_ serviceUUIDs: [CBUUID]?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) discoverServices( + serviceUUIDs: \(String(describing: serviceUUIDs?.logDescription))) + """) + peripheral.discoverServices(serviceUUIDs) + } + + func discoverCharacteristics(_ characteristicUUIDs: [CBUUID]?, for service: RxServiceType) { + let cbService = (service as! RxCBService).service + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) discoverCharacteristics( + characteristicUUIDs: \(String(describing: characteristicUUIDs?.logDescription)), + for: \(cbService.logDescription)) + """) + peripheral.discoverCharacteristics(characteristicUUIDs, for: cbService) + } + + func discoverIncludedServices(_ includedServiceUUIDs: [CBUUID]?, for service: RxServiceType) { + let cbService = (service as! RxCBService).service + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) discoverIncludedServices( + includedServiceUUIDs: \(String(describing: includedServiceUUIDs?.logDescription)), + for: \(cbService.logDescription)) + """) + peripheral.discoverIncludedServices(includedServiceUUIDs, for: cbService) + } + + func readValue(for characteristic: RxCharacteristicType) { + let cbcharacteristic = (characteristic as! RxCBCharacteristic).characteristic + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) readValue( + for: \(cbcharacteristic.logDescription)) + """) + peripheral.readValue(for: cbcharacteristic) + } + + func writeValue(_ data: Data, + for characteristic: RxCharacteristicType, + type: CBCharacteristicWriteType) { + let cbcharacteristic = (characteristic as! RxCBCharacteristic).characteristic + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) writeValue( + data: \(data.logDescription), + for: \(cbcharacteristic.logDescription), + type: \(type.logDescription)) + """) + peripheral.writeValue(data, for: cbcharacteristic, type: type) + } + + func setNotifyValue(_ enabled: Bool, for characteristic: RxCharacteristicType) { + let cbcharacteristic = (characteristic as! RxCBCharacteristic).characteristic + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) setNotifyValue( + enabled: \(enabled), + for: \(cbcharacteristic.logDescription)) + """) + peripheral.setNotifyValue(enabled, for: cbcharacteristic) + } + + func discoverDescriptors(for characteristic: RxCharacteristicType) { + let cbcharacteristic = (characteristic as! RxCBCharacteristic).characteristic + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) discoverDescriptors( + for: \(cbcharacteristic.logDescription)) + """) + peripheral.discoverDescriptors(for: cbcharacteristic) + } + + func readValue(for descriptor: RxDescriptorType) { + let cbdescriptor = (descriptor as! RxCBDescriptor).descriptor + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) readValue( + for: \(cbdescriptor.logDescription)) + """) + peripheral.readValue(for: cbdescriptor) + } + + @available(OSX 10.12, iOS 9.0, *) + func maximumWriteValueLength(for type: CBCharacteristicWriteType) -> Int { + return peripheral.maximumWriteValueLength(for: type) + } + + func writeValue(_ data: Data, for descriptor: RxDescriptorType) { + let cbdescriptor = (descriptor as! RxCBDescriptor).descriptor + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) writeValue( + data: \(data.logDescription), + for: \(cbdescriptor.logDescription)) + """) + peripheral.writeValue(data, for: cbdescriptor) + } + + func readRSSI() { + RxBluetoothKitLog.d("\(peripheral.logDescription) readRSSI()") + peripheral.readRSSI() + } + + @objc fileprivate class InternalPeripheralDelegate: NSObject, CBPeripheralDelegate { + let peripheralDidUpdateNameSubject = PublishSubject() + let peripheralDidModifyServicesSubject = PublishSubject<([RxServiceType])>() + let peripheralDidReadRSSISubject = PublishSubject<(Int, Error?)>() + let peripheralDidDiscoverServicesSubject = PublishSubject<([RxServiceType]?, Error?)>() + let peripheralDidDiscoverIncludedServicesForServiceSubject = PublishSubject<(RxServiceType, Error?)>() + let peripheralDidDiscoverCharacteristicsForServiceSubject = PublishSubject<(RxServiceType, Error?)>() + let peripheralDidUpdateValueForCharacteristicSubject = PublishSubject<(RxCharacteristicType, Error?)>() + let peripheralDidWriteValueForCharacteristicSubject = PublishSubject<(RxCharacteristicType, Error?)>() + let peripheralDidUpdateNotificationStateForCharacteristicSubject = + PublishSubject<(RxCharacteristicType, Error?)>() + let peripheralDidDiscoverDescriptorsForCharacteristicSubject = + PublishSubject<(RxCharacteristicType, Error?)>() + let peripheralDidUpdateValueForDescriptorSubject = PublishSubject<(RxDescriptorType, Error?)>() + let peripheralDidWriteValueForDescriptorSubject = PublishSubject<(RxDescriptorType, Error?)>() + let peripheralIsReadyToSendWriteWithoutResponseSubject = PublishSubject() + + @objc func peripheralDidUpdateName(_ peripheral: CBPeripheral) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didUpdateName(name: \(String(describing: peripheral.name))) + """) + peripheralDidUpdateNameSubject.onNext(peripheral.name) + } + + @objc func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didModifyServices(services: + [\(invalidatedServices.logDescription))] + """) + peripheralDidModifyServicesSubject.onNext(invalidatedServices.compactMap(RxCBService.init)) + } + + @objc func peripheral(_ peripheral: CBPeripheral, didReadRSSI rssi: NSNumber, error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didReadRSSI(rssi: \(rssi), + error: \(String(describing: error))) + """) + peripheralDidReadRSSISubject.onNext((rssi.intValue, error)) + } + + @objc func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didDiscoverServices(services + : \(String(describing: peripheral.services?.logDescription)), + error: \(String(describing: error))) + """) + peripheralDidDiscoverServicesSubject.onNext((peripheral.services?.compactMap(RxCBService.init), error)) + } + + @objc func peripheral(_ peripheral: CBPeripheral, + didDiscoverIncludedServicesFor service: CBService, + error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didDiscoverIncludedServices(for: + \(service.logDescription), includedServices: + \(String(describing: service.includedServices?.logDescription)), + error: \(String(describing: error))) + """) + peripheralDidDiscoverIncludedServicesForServiceSubject.onNext((RxCBService(service: service), error)) + } + + @objc func peripheral(_ peripheral: CBPeripheral, + didDiscoverCharacteristicsFor service: CBService, + error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didDiscoverCharacteristicsFor(for: + \(service.logDescription), characteristics: + \(String(describing: service.characteristics?.logDescription)), + error: \(String(describing: error))) + """) + peripheralDidDiscoverCharacteristicsForServiceSubject.onNext((RxCBService(service: service), error)) + } + + @objc func peripheral(_ peripheral: CBPeripheral, + didUpdateValueFor characteristic: CBCharacteristic, + error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didUpdateValueFor(for:\(characteristic.logDescription), + value: \(String(describing: characteristic.value?.logDescription)), + error: \(String(describing: error))) + """) + peripheralDidUpdateValueForCharacteristicSubject + .onNext((RxCBCharacteristic(characteristic: characteristic), error)) + } + + @objc func peripheral(_ peripheral: CBPeripheral, + didWriteValueFor characteristic: CBCharacteristic, + error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didWriteValueFor(for:\(characteristic.logDescription), + value: \(String(describing: characteristic.value?.logDescription)), + error: \(String(describing: error))) + """) + peripheralDidWriteValueForCharacteristicSubject + .onNext((RxCBCharacteristic(characteristic: characteristic), error)) + } + + @objc func peripheral(_ peripheral: CBPeripheral, + didUpdateNotificationStateFor characteristic: CBCharacteristic, + error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didUpdateNotificationStateFor( + for:\(characteristic.logDescription), isNotifying: \(characteristic.isNotifying), + error: \(String(describing: error))) + """) + peripheralDidUpdateNotificationStateForCharacteristicSubject + .onNext((RxCBCharacteristic(characteristic: characteristic), error)) + } + + @objc func peripheral(_ peripheral: CBPeripheral, + didDiscoverDescriptorsFor characteristic: CBCharacteristic, + error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didDiscoverDescriptorsFor + (for:\(characteristic.logDescription), descriptors: + \(String(describing: characteristic.descriptors?.logDescription)), + error: \(String(describing: error))) + """) + peripheralDidDiscoverDescriptorsForCharacteristicSubject + .onNext((RxCBCharacteristic(characteristic: characteristic), error)) + } + + @objc func peripheral(_ peripheral: CBPeripheral, + didUpdateValueFor descriptor: CBDescriptor, + error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didUpdateValueFor(for:\(descriptor.logDescription), + value: \(String(describing: descriptor.value)), error: \(String(describing: error))) + """) + peripheralDidUpdateValueForDescriptorSubject.onNext((RxCBDescriptor(descriptor: descriptor), error)) + } + + @objc func peripheral(_ peripheral: CBPeripheral, + didWriteValueFor descriptor: CBDescriptor, + error: Error?) { + RxBluetoothKitLog.d(""" + \(peripheral.logDescription) didWriteValueFor(for:\(descriptor.logDescription), + error: \(String(describing: error))) + """) + peripheralDidWriteValueForDescriptorSubject.onNext((RxCBDescriptor(descriptor: descriptor), error)) + } + + @objc func peripheralIsReady(toSendWriteWithoutResponse peripheral: CBPeripheral) { + //resolve build errors with XCode 11 / iOS 13 + let canSendWriteWithoutResponse: Bool + if #available(iOS 11.2, *) { + canSendWriteWithoutResponse = peripheral.canSendWriteWithoutResponse + } else { + canSendWriteWithoutResponse = true + } + RxBluetoothKitLog.d("\(peripheral.logDescription) peripheralIsReady(toSendWriteWithoutResponse:\(canSendWriteWithoutResponse)") + peripheralIsReadyToSendWriteWithoutResponseSubject.onNext(canSendWriteWithoutResponse) + } + } + + fileprivate class InternalPeripheralDelegateWrapper { + fileprivate let delegate: InternalPeripheralDelegate + fileprivate var refCount: Int + + fileprivate init(delegate: InternalPeripheralDelegate) { + self.delegate = delegate + refCount = 1 + } + } + + private static let internalPeripheralDelegateWrappersLock = NSLock() + private static var internalPeripheralDelegateWrappers = [CBPeripheral: InternalPeripheralDelegateWrapper]() + + private static func getInternalPeripheralDelegateRef(cbPeripheral: CBPeripheral) -> InternalPeripheralDelegate { + internalPeripheralDelegateWrappersLock.lock(); defer { internalPeripheralDelegateWrappersLock.unlock() } + + if let wrapper = internalPeripheralDelegateWrappers[cbPeripheral] { + wrapper.refCount += 1 + return wrapper.delegate + } else { + let delegate = InternalPeripheralDelegate() + cbPeripheral.delegate = delegate + internalPeripheralDelegateWrappers[cbPeripheral] = InternalPeripheralDelegateWrapper(delegate: delegate) + return delegate + } + } + + fileprivate static func putInternalPeripheralDelegateRef(cbPeripheral: CBPeripheral) { + internalPeripheralDelegateWrappersLock.lock(); defer { internalPeripheralDelegateWrappersLock.unlock() } + + if let wrapper = internalPeripheralDelegateWrappers[cbPeripheral] { + wrapper.refCount -= 1 + if wrapper.refCount == 0 { + cbPeripheral.delegate = nil + internalPeripheralDelegateWrappers[cbPeripheral] = nil + } + } else { + fatalError("Implementation error: internal delegate for CBPeripheral is cached in memory") + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBService.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBService.swift new file mode 100644 index 000000000..9272de5c7 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCBService.swift @@ -0,0 +1,42 @@ +import Foundation +import CoreBluetooth + +class RxCBService: RxServiceType { + + let service: CBService + init(service: CBService) { + self.service = service + } + + init?(service: CBService?) { + guard let service = service else { + return nil + } + self.service = service + } + + var objectId: UInt { + return UInt(bitPattern: ObjectIdentifier(service)) + } + + var uuid: CBUUID { + return service.uuid + } + + var characteristics: [RxCharacteristicType]? { + return service.characteristics?.compactMap(RxCBCharacteristic.init) + } + + var includedServices: [RxServiceType]? { + return service.includedServices?.compactMap(RxCBService.init) + } + + var isPrimary: Bool { + return service.isPrimary + } + + func isEqualTo(service: RxServiceType) -> Bool { + guard let rhs = service as? RxCBService else { return false } + return self.service === rhs.service + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCentralManagerType.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCentralManagerType.swift new file mode 100644 index 000000000..d96e96598 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCentralManagerType.swift @@ -0,0 +1,23 @@ +import Foundation +import CoreBluetooth + +protocol RxCentralManagerType { + + @available(*, deprecated) + var objectId: UInt { get } + var rx_didUpdateState: Observable { get } + var rx_willRestoreState: Observable<[String: Any]> { get } + var rx_didDiscoverPeripheral: Observable<(RxPeripheralType, [String: Any], NSNumber)> { get } + var rx_didConnectPeripheral: Observable { get } + var rx_didFailToConnectPeripheral: Observable<(RxPeripheralType, Error?)> { get } + var rx_didDisconnectPeripheral: Observable<(RxPeripheralType, Error?)> { get } + var state: BluetoothState { get } + var centralManager: CBCentralManager { get } + + func scanForPeripherals(withServices serviceUUIDs: [CBUUID]?, options: [String: Any]?) + func connect(_ peripheral: RxPeripheralType, options: [String: Any]?) + func cancelPeripheralConnection(_ peripheral: RxPeripheralType) + func stopScan() + func retrieveConnectedPeripherals(withServices serviceUUIDs: [CBUUID]) -> Observable<[RxPeripheralType]> + func retrievePeripherals(withIdentifiers identifiers: [UUID]) -> Observable<[RxPeripheralType]> +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCharacteristicType.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCharacteristicType.swift new file mode 100644 index 000000000..97560e135 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxCharacteristicType.swift @@ -0,0 +1,24 @@ +import Foundation +import CoreBluetooth + +protocol RxCharacteristicType { + var objectId: UInt { get } + var uuid: CBUUID { get } + var value: Data? { get } + var isNotifying: Bool { get } + var properties: CBCharacteristicProperties { get } + var descriptors: [RxDescriptorType]? { get } + var service: RxServiceType? { get } + + func isEqualTo(characteristic: RxCharacteristicType) -> Bool +} + +extension Equatable where Self: RxCharacteristicType {} + +func == (lhs: RxCharacteristicType, rhs: RxCharacteristicType) -> Bool { + return lhs.isEqualTo(characteristic: rhs) +} + +func == (lhs: [RxCharacteristicType], rhs: [RxCharacteristicType]) -> Bool { + return lhs.count == rhs.count && lhs.starts(with: rhs, by: ==) +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxDescriptorType.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxDescriptorType.swift new file mode 100644 index 000000000..0e2cd73db --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxDescriptorType.swift @@ -0,0 +1,21 @@ +import Foundation +import CoreBluetooth + +protocol RxDescriptorType { + + var objectId: UInt { get } + + var uuid: CBUUID { get } + + var characteristic: RxCharacteristicType? { get } + + var value: Any? { get } + + func isEqualTo(descriptor: RxDescriptorType) -> Bool +} + +extension Equatable where Self: RxDescriptorType {} + +func == (lhs: RxDescriptorType, rhs: RxDescriptorType) -> Bool { + return lhs.isEqualTo(descriptor: rhs) +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxPeripheralType.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxPeripheralType.swift new file mode 100644 index 000000000..dd8c060f8 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxPeripheralType.swift @@ -0,0 +1,76 @@ +import Foundation +import CoreBluetooth + +protocol RxPeripheralType { + + var name: String? { get } + + var identifier: UUID { get } + + var objectId: UInt { get } + + var peripheral: CBPeripheral { get } + + var state: CBPeripheralState { get } + + var services: [RxServiceType]? { get } + + var canSendWriteWithoutResponse: Bool { get } + + var rx_didUpdateName: Observable { get } + + var rx_didModifyServices: Observable<([RxServiceType])> { get } + + var rx_didReadRSSI: Observable<(Int, Error?)> { get } + + var rx_didDiscoverServices: Observable<([RxServiceType]?, Error?)> { get } + + var rx_didDiscoverIncludedServicesForService: Observable<(RxServiceType, Error?)> { get } + + var rx_didDiscoverCharacteristicsForService: Observable<(RxServiceType, Error?)> { get } + + var rx_didUpdateValueForCharacteristic: Observable<(RxCharacteristicType, Error?)> { get } + + var rx_didWriteValueForCharacteristic: Observable<(RxCharacteristicType, Error?)> { get } + + var rx_didUpdateNotificationStateForCharacteristic: Observable<(RxCharacteristicType, Error?)> { get } + + var rx_didDiscoverDescriptorsForCharacteristic: Observable<(RxCharacteristicType, Error?)> { get } + + var rx_didUpdateValueForDescriptor: Observable<(RxDescriptorType, Error?)> { get } + + var rx_didWriteValueForDescriptor: Observable<(RxDescriptorType, Error?)> { get } + + var rx_isReadyToSendWriteWithoutResponse: Observable { get } + + func discoverServices(_ serviceUUIDs: [CBUUID]?) + + func discoverCharacteristics(_ characteristicUUIDs: [CBUUID]?, for service: RxServiceType) + + func discoverIncludedServices(_ includedServiceUUIDs: [CBUUID]?, for service: RxServiceType) + + func readValue(for characteristic: RxCharacteristicType) + + @available(OSX 10.12, iOS 9.0, *) + func maximumWriteValueLength(for type: CBCharacteristicWriteType) -> Int + + func writeValue(_ data: Data, + for characteristic: RxCharacteristicType, + type: CBCharacteristicWriteType) + + func setNotifyValue(_ enabled: Bool, for characteristic: RxCharacteristicType) + + func discoverDescriptors(for characteristic: RxCharacteristicType) + + func readValue(for descriptor: RxDescriptorType) + + func writeValue(_ data: Data, for descriptor: RxDescriptorType) + + func readRSSI() +} + +extension Equatable where Self: RxPeripheralType {} + +func == (lhs: RxPeripheralType, rhs: RxPeripheralType) -> Bool { + return lhs.identifier == rhs.identifier +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxServiceType.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxServiceType.swift new file mode 100644 index 000000000..6d5892ca2 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/RxServiceType.swift @@ -0,0 +1,21 @@ +import Foundation +import CoreBluetooth + +protocol RxServiceType { + var objectId: UInt { get } + var uuid: CBUUID { get } + var characteristics: [RxCharacteristicType]? { get } + var includedServices: [RxServiceType]? { get } + var isPrimary: Bool { get } + func isEqualTo(service: RxServiceType) -> Bool +} + +extension Equatable where Self: RxServiceType {} + +func == (lhs: RxServiceType, rhs: RxServiceType) -> Bool { + return lhs.isEqualTo(service: rhs) +} + +func == (lhs: [RxServiceType], rhs: [RxServiceType]) -> Bool { + return lhs.count == rhs.count && lhs.starts(with: rhs, by: ==) +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/ScanOperation.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/ScanOperation.swift new file mode 100644 index 000000000..eaccef678 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/ScanOperation.swift @@ -0,0 +1,30 @@ +import Foundation +import CoreBluetooth + +final class ScanOperation { + let uuids: [CBUUID]? + let observable: Observable + init(uuids: [CBUUID]?, observable: Observable) { + self.uuids = uuids + self.observable = observable + } +} + +extension ScanOperation { + func shouldAccept(_ newUUIDs: [CBUUID]?) -> Bool { + guard let uuids = uuids else { + return true + } + guard let newUUIDs = newUUIDs else { + return false + } + return Set(uuids).isSuperset(of: Set(newUUIDs)) + } +} + +func == (lhs: ScanOperation, rhs: ScanOperation) -> Bool { + if lhs.uuids == nil { + return rhs.uuids == nil + } + return rhs.uuids != nil && rhs.uuids! == lhs.uuids! +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/ScannedPeripheral.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/ScannedPeripheral.swift new file mode 100644 index 000000000..0d80848a7 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/ScannedPeripheral.swift @@ -0,0 +1,22 @@ +import Foundation +import CoreBluetooth + +/// Represents instance of scanned peripheral - containing it's advertisment data, rssi and peripheral itself. +/// To perform further actions `peripheral` instance variable can be used ia. to maintain connection. +public class ScannedPeripheral { + + /// `Peripheral` instance, that allows to perform further bluetooth actions. + public let peripheral: Peripheral + + /// Advertisement data of scanned peripheral + public let advertisementData: AdvertisementData + + /// Scanned peripheral's RSSI value. + public let rssi: NSNumber + + init(peripheral: Peripheral, advertisementData: AdvertisementData, rssi: NSNumber) { + self.peripheral = peripheral + self.advertisementData = advertisementData + self.rssi = rssi + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Service.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Service.swift new file mode 100644 index 000000000..57e938617 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Service.swift @@ -0,0 +1,75 @@ +import Foundation +import CoreBluetooth + +// swiftlint:disable line_length +/// Service is a class implementing ReactiveX which wraps CoreBluetooth functions related to interaction with [CBService](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBService_Class/) +public class Service { + let service: RxServiceType + + /// Peripheral to which this service belongs + public let peripheral: Peripheral + + /// True if service is primary service + public var isPrimary: Bool { + return service.isPrimary + } + + /// Unique identifier of an object. + public var objectId: UInt { + return service.objectId + } + + /// Service's UUID + public var uuid: CBUUID { + return service.uuid + } + + /// Service's included services + public var includedServices: [Service]? { + return service.includedServices?.map { + Service(peripheral: peripheral, service: $0) + } + } + + /// Service's characteristics + public var characteristics: [Characteristic]? { + return service.characteristics?.map { + Characteristic(characteristic: $0, service: self) + } + } + + init(peripheral: Peripheral, service: RxServiceType) { + self.service = service + self.peripheral = peripheral + } + + /// Function that triggers characteristics discovery for specified Services and identifiers. Discovery is called after + /// subscribtion to `Observable` is made. + /// - Parameter identifiers: Identifiers of characteristics that should be discovered. If `nil` - all of the + /// characteristics will be discovered. If you'll pass empty array - none of them will be discovered. + /// - Returns: Observable that emits `Next` with array of `Characteristic` instances, once they're discovered. + /// Immediately after that `.Complete` is emitted. + public func discoverCharacteristics(_ characteristicUUIDs: [CBUUID]?) -> Observable<[Characteristic]> { + return peripheral.discoverCharacteristics(characteristicUUIDs, for: self) + } + + /// Function that triggers included services discovery for specified services. Discovery is called after + /// subscribtion to `Observable` is made. + /// - Parameter includedServiceUUIDs: Identifiers of included services that should be discovered. If `nil` - all of the + /// included services will be discovered. If you'll pass empty array - none of them will be discovered. + /// - Returns: Observable that emits `Next` with array of `Service` instances, once they're discovered. + /// Immediately after that `.Complete` is emitted. + public func discoverIncludedServices(_ includedServiceUUIDs: [CBUUID]?) -> Observable<[Service]> { + return peripheral.discoverIncludedServices(includedServiceUUIDs, for: self) + } +} + +extension Service: Equatable {} + +/// Compare if services are equal. They are if theirs uuids are the same. +/// - parameter lhs: First service +/// - parameter rhs: Second service +/// - returns: True if services are the same. +public func == (lhs: Service, rhs: Service) -> Bool { + return lhs.service == rhs.service +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/UUIDIdentifiable.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/UUIDIdentifiable.swift new file mode 100644 index 000000000..59809b047 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/UUIDIdentifiable.swift @@ -0,0 +1,25 @@ +import Foundation +import CoreBluetooth + +protocol UUIDIdentifiable { + var uuid: CBUUID { get } +} + +extension Characteristic: UUIDIdentifiable {} +extension Service: UUIDIdentifiable {} + +/// Filters an item list based on the provided UUID list. The items must conform to UUIDIdentifiable. +/// Only items returned whose UUID matches an item in the provided UUID list. +/// Each UUID should have at least one item matching in the items list. Otherwise the result is nil. + +/// - uuids: a UUID list or nil +/// - items: items to be filtered +/// - Returns: the filtered item list +func filterUUIDItems(uuids: [CBUUID]?, items: [T]) -> [T]? { + guard let uuids = uuids, !uuids.isEmpty else { return items } + + let itemsUUIDs = items.map { $0.uuid } + let uuidsSet = Set(uuids) + guard uuidsSet.isSubset(of: Set(itemsUUIDs)) else { return nil } + return items.filter { uuidsSet.contains($0.uuid) } +} \ No newline at end of file diff --git a/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Unimplemented.swift b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Unimplemented.swift new file mode 100644 index 000000000..d6096194e --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxBluetoothKit/Unimplemented.swift @@ -0,0 +1,13 @@ +import Foundation + +func unimplementedFunction(file: String = #file, function: String = #function, line: Int = #line) { + fatalError("Unimplemented function \(function) in \(file):\(line)") +} + +extension Observable { + static func unimplemented(file: String = #file, function: String = #function, line: Int = #line) + -> Observable { + unimplementedFunction(file: file, function: function, line: line) + return Observable.empty() + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/AnyObserver.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/AnyObserver.swift new file mode 100644 index 000000000..e92cc816e --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/AnyObserver.swift @@ -0,0 +1,69 @@ +// +// AnyObserver.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// A type-erased `ObserverType`. +/// +/// Forwards operations to an arbitrary underlying observer with the same `Element` type, hiding the specifics of the underlying observer type. +public struct AnyObserver : ObserverType { + /// Anonymous event handler type. + public typealias EventHandler = (Event) -> Void + + private let observer: EventHandler + + /// Construct an instance whose `on(event)` calls `eventHandler(event)` + /// + /// - parameter eventHandler: Event handler that observes sequences events. + public init(eventHandler: @escaping EventHandler) { + self.observer = eventHandler + } + + /// Construct an instance whose `on(event)` calls `observer.on(event)` + /// + /// - parameter observer: Observer that receives sequence events. + public init(_ observer: Observer) where Observer.Element == Element { + self.observer = observer.on + } + + /// Send `event` to this observer. + /// + /// - parameter event: Event instance. + public func on(_ event: Event) { + self.observer(event) + } + + /// Erases type of observer and returns canonical observer. + /// + /// - returns: type erased observer. + public func asObserver() -> AnyObserver { + self + } +} + +extension AnyObserver { + /// Collection of `AnyObserver`s + typealias s = Bag<(Event) -> Void> +} + +extension ObserverType { + /// Erases type of observer and returns canonical observer. + /// + /// - returns: type erased observer. + public func asObserver() -> AnyObserver { + AnyObserver(self) + } + + /// Transforms observer of type R to type E using custom transform method. + /// Each event sent to result observer is transformed and sent to `self`. + /// + /// - returns: observer that transforms events. + public func mapObserver(_ transform: @escaping (Result) throws -> Element) -> AnyObserver { + AnyObserver { e in + self.on(e.map(transform)) + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Binder.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Binder.swift new file mode 100644 index 000000000..1aae09592 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Binder.swift @@ -0,0 +1,59 @@ +// +// Binder.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/17/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +/** + Observer that enforces interface binding rules: + * can't bind errors (in debug builds binding of errors causes `fatalError` in release builds errors are being logged) + * ensures binding is performed on a specific scheduler + + `Binder` doesn't retain target and in case target is released, element isn't bound. + + By default it binds elements on main scheduler. + */ +public struct Binder: ObserverType { + public typealias Element = Value + + private let binding: (Event) -> Void + + /// Initializes `Binder` + /// + /// - parameter target: Target object. + /// - parameter scheduler: Scheduler used to bind the events. + /// - parameter binding: Binding logic. + public init(_ target: Target, scheduler: ImmediateSchedulerType = MainScheduler(), binding: @escaping (Target, Value) -> Void) { + weak var weakTarget = target + + self.binding = { event in + switch event { + case .next(let element): + _ = scheduler.schedule(element) { element in + if let target = weakTarget { + binding(target, element) + } + return Disposables.create() + } + case .error(let error): + rxFatalErrorInDebug("Binding error: \(error)") + case .completed: + break + } + } + } + + /// Binds next element to owner view as described in `binding`. + public func on(_ event: Event) { + self.binding(event) + } + + /// Erases type of observer. + /// + /// - returns: type erased observer. + public func asObserver() -> AnyObserver { + AnyObserver(eventHandler: self.on) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Cancelable.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Cancelable.swift new file mode 100644 index 000000000..1fa7a6772 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Cancelable.swift @@ -0,0 +1,13 @@ +// +// Cancelable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents disposable resource with state tracking. +public protocol Cancelable : Disposable { + /// Was resource disposed. + var isDisposed: Bool { get } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/AsyncLock.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/AsyncLock.swift new file mode 100644 index 000000000..502597e93 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/AsyncLock.swift @@ -0,0 +1,100 @@ +// +// AsyncLock.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +In case nobody holds this lock, the work will be queued and executed immediately +on thread that is requesting lock. + +In case there is somebody currently holding that lock, action will be enqueued. +When owned of the lock finishes with it's processing, it will also execute +and pending work. + +That means that enqueued work could possibly be executed later on a different thread. +*/ +final class AsyncLock + : Disposable + , Lock + , SynchronizedDisposeType { + typealias Action = () -> Void + + private var _lock = SpinLock() + + private var queue: Queue = Queue(capacity: 0) + + private var isExecuting: Bool = false + private var hasFaulted: Bool = false + + // lock { + func lock() { + self._lock.lock() + } + + func unlock() { + self._lock.unlock() + } + // } + + private func enqueue(_ action: I) -> I? { + self.lock(); defer { self.unlock() } + if self.hasFaulted { + return nil + } + + if self.isExecuting { + self.queue.enqueue(action) + return nil + } + + self.isExecuting = true + + return action + } + + private func dequeue() -> I? { + self.lock(); defer { self.unlock() } + if !self.queue.isEmpty { + return self.queue.dequeue() + } + else { + self.isExecuting = false + return nil + } + } + + func invoke(_ action: I) { + let firstEnqueuedAction = self.enqueue(action) + + if let firstEnqueuedAction = firstEnqueuedAction { + firstEnqueuedAction.invoke() + } + else { + // action is enqueued, it's somebody else's concern now + return + } + + while true { + let nextAction = self.dequeue() + + if let nextAction = nextAction { + nextAction.invoke() + } + else { + return + } + } + } + + func dispose() { + self.synchronizedDispose() + } + + func synchronized_dispose() { + self.queue = Queue(capacity: 0) + self.hasFaulted = true + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/Lock.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/Lock.swift new file mode 100644 index 000000000..7232f23f5 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/Lock.swift @@ -0,0 +1,23 @@ +// +// Lock.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol Lock { + func lock() + func unlock() +} + +// https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000321.html +typealias SpinLock = RecursiveLock + +extension RecursiveLock : Lock { + @inline(__always) + final func performLocked(_ action: () -> T) -> T { + self.lock(); defer { self.unlock() } + return action() + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/LockOwnerType.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/LockOwnerType.swift new file mode 100644 index 000000000..8a98007d1 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/LockOwnerType.swift @@ -0,0 +1,16 @@ +// +// LockOwnerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol LockOwnerType: AnyObject, Lock { + var lock: RecursiveLock { get } +} + +extension LockOwnerType { + func lock() { self.lock.lock() } + func unlock() { self.lock.unlock() } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/SynchronizedDisposeType.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/SynchronizedDisposeType.swift new file mode 100644 index 000000000..527a2fbe8 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/SynchronizedDisposeType.swift @@ -0,0 +1,18 @@ +// +// SynchronizedDisposeType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedDisposeType: AnyObject, Disposable, Lock { + func synchronized_dispose() +} + +extension SynchronizedDisposeType { + func synchronizedDispose() { + self.lock(); defer { self.unlock() } + self.synchronized_dispose() + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/SynchronizedOnType.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/SynchronizedOnType.swift new file mode 100644 index 000000000..19168d776 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/SynchronizedOnType.swift @@ -0,0 +1,18 @@ +// +// SynchronizedOnType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedOnType: AnyObject, ObserverType, Lock { + func synchronized_on(_ event: Event) +} + +extension SynchronizedOnType { + func synchronizedOn(_ event: Event) { + self.lock(); defer { self.unlock() } + self.synchronized_on(event) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift new file mode 100644 index 000000000..988b86f4d --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift @@ -0,0 +1,13 @@ +// +// SynchronizedUnsubscribeType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedUnsubscribeType: AnyObject { + associatedtype DisposeKey + + func synchronizedUnsubscribe(_ disposeKey: DisposeKey) +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/ConnectableObservableType.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/ConnectableObservableType.swift new file mode 100644 index 000000000..52bf93c56 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/ConnectableObservableType.swift @@ -0,0 +1,19 @@ +// +// ConnectableObservableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Represents an observable sequence wrapper that can be connected and disconnected from its underlying observable sequence. +*/ +public protocol ConnectableObservableType : ObservableType { + /** + Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established. + + - returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence. + */ + func connect() -> Disposable +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Date+Dispatch.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Date+Dispatch.swift new file mode 100644 index 000000000..90f70c560 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Date+Dispatch.swift @@ -0,0 +1,64 @@ +// +// Date+Dispatch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/14/19. +// Copyright © 2019 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +extension DispatchTimeInterval { + var convertToSecondsFactor: Double { + switch self { + case .nanoseconds: return 1_000_000_000.0 + case .microseconds: return 1_000_000.0 + case .milliseconds: return 1_000.0 + case .seconds: return 1.0 + case .never: fatalError() + @unknown default: fatalError() + } + } + + func map(_ transform: (Int, Double) -> Int) -> DispatchTimeInterval { + switch self { + case .nanoseconds(let value): return .nanoseconds(transform(value, 1_000_000_000.0)) + case .microseconds(let value): return .microseconds(transform(value, 1_000_000.0)) + case .milliseconds(let value): return .milliseconds(transform(value, 1_000.0)) + case .seconds(let value): return .seconds(transform(value, 1.0)) + case .never: return .never + @unknown default: fatalError() + } + } + + var isNow: Bool { + switch self { + case .nanoseconds(let value), .microseconds(let value), .milliseconds(let value), .seconds(let value): return value == 0 + case .never: return false + @unknown default: fatalError() + } + } + + internal func reduceWithSpanBetween(earlierDate: Date, laterDate: Date) -> DispatchTimeInterval { + return self.map { value, factor in + let interval = laterDate.timeIntervalSince(earlierDate) + let remainder = Double(value) - interval * factor + guard remainder > 0 else { return 0 } + return Int(remainder.rounded(.toNearestOrAwayFromZero)) + } + } +} + +extension Date { + + internal func addingDispatchInterval(_ dispatchInterval: DispatchTimeInterval) -> Date { + switch dispatchInterval { + case .nanoseconds(let value), .microseconds(let value), .milliseconds(let value), .seconds(let value): + return self.addingTimeInterval(TimeInterval(value) / dispatchInterval.convertToSecondsFactor) + case .never: return Date.distantFuture + @unknown default: fatalError() + } + } + +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposable.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposable.swift new file mode 100644 index 000000000..b79c77a75 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposable.swift @@ -0,0 +1,13 @@ +// +// Disposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource. +public protocol Disposable { + /// Dispose resource. + func dispose() +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/AnonymousDisposable.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/AnonymousDisposable.swift new file mode 100644 index 000000000..591aafa5e --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/AnonymousDisposable.swift @@ -0,0 +1,59 @@ +// +// AnonymousDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an Action-based disposable. +/// +/// When dispose method is called, disposal action will be dereferenced. +private final class AnonymousDisposable : DisposeBase, Cancelable { + public typealias DisposeAction = () -> Void + + private let disposed = AtomicInt(0) + private var disposeAction: DisposeAction? + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + isFlagSet(self.disposed, 1) + } + + /// Constructs a new disposable with the given action used for disposal. + /// + /// - parameter disposeAction: Disposal action which will be run upon calling `dispose`. + private init(_ disposeAction: @escaping DisposeAction) { + self.disposeAction = disposeAction + super.init() + } + + // Non-deprecated version of the constructor, used by `Disposables.create(with:)` + fileprivate init(disposeAction: @escaping DisposeAction) { + self.disposeAction = disposeAction + super.init() + } + + /// Calls the disposal action if and only if the current instance hasn't been disposed yet. + /// + /// After invoking disposal action, disposal action will be dereferenced. + fileprivate func dispose() { + if fetchOr(self.disposed, 1) == 0 { + if let action = self.disposeAction { + self.disposeAction = nil + action() + } + } + } +} + +extension Disposables { + + /// Constructs a new disposable with the given action used for disposal. + /// + /// - parameter dispose: Disposal action which will be run upon calling `dispose`. + public static func create(with dispose: @escaping () -> Void) -> Cancelable { + AnonymousDisposable(disposeAction: dispose) + } + +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/BinaryDisposable.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/BinaryDisposable.swift new file mode 100644 index 000000000..a3d493708 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/BinaryDisposable.swift @@ -0,0 +1,53 @@ +// +// BinaryDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents two disposable resources that are disposed together. +private final class BinaryDisposable : DisposeBase, Cancelable { + + private let disposed = AtomicInt(0) + + // state + private var disposable1: Disposable? + private var disposable2: Disposable? + + /// - returns: Was resource disposed. + var isDisposed: Bool { + isFlagSet(self.disposed, 1) + } + + /// Constructs new binary disposable from two disposables. + /// + /// - parameter disposable1: First disposable + /// - parameter disposable2: Second disposable + init(_ disposable1: Disposable, _ disposable2: Disposable) { + self.disposable1 = disposable1 + self.disposable2 = disposable2 + super.init() + } + + /// Calls the disposal action if and only if the current instance hasn't been disposed yet. + /// + /// After invoking disposal action, disposal action will be dereferenced. + func dispose() { + if fetchOr(self.disposed, 1) == 0 { + self.disposable1?.dispose() + self.disposable2?.dispose() + self.disposable1 = nil + self.disposable2 = nil + } + } +} + +extension Disposables { + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable) -> Cancelable { + BinaryDisposable(disposable1, disposable2) + } + +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/BooleanDisposable.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/BooleanDisposable.swift new file mode 100644 index 000000000..5efcbea2e --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/BooleanDisposable.swift @@ -0,0 +1,34 @@ +// +// BooleanDisposable.swift +// RxSwift +// +// Created by Junior B. on 10/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource that can be checked for disposal status. +public final class BooleanDisposable : Cancelable { + + internal static let BooleanDisposableTrue = BooleanDisposable(isDisposed: true) + private let disposed: AtomicInt + + /// Initializes a new instance of the `BooleanDisposable` class + public init() { + disposed = AtomicInt(0) + } + + /// Initializes a new instance of the `BooleanDisposable` class with given value + public init(isDisposed: Bool) { + self.disposed = AtomicInt(isDisposed ? 1 : 0) + } + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + isFlagSet(self.disposed, 1) + } + + /// Sets the status to disposed, which can be observer through the `isDisposed` property. + public func dispose() { + fetchOr(self.disposed, 1) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/CompositeDisposable.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/CompositeDisposable.swift new file mode 100644 index 000000000..bb4efe6ac --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/CompositeDisposable.swift @@ -0,0 +1,147 @@ +// +// CompositeDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a group of disposable resources that are disposed together. +public final class CompositeDisposable : DisposeBase, Cancelable { + /// Key used to remove disposable from composite disposable + public struct DisposeKey { + fileprivate let key: BagKey + fileprivate init(key: BagKey) { + self.key = key + } + } + + private var lock = SpinLock() + + // state + private var disposables: Bag? = Bag() + + public var isDisposed: Bool { + self.lock.performLocked { self.disposables == nil } + } + + public override init() { + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(_ disposable1: Disposable, _ disposable2: Disposable) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _ = self.disposables!.insert(disposable1) + _ = self.disposables!.insert(disposable2) + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _ = self.disposables!.insert(disposable1) + _ = self.disposables!.insert(disposable2) + _ = self.disposables!.insert(disposable3) + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposable4: Disposable, _ disposables: Disposable...) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _ = self.disposables!.insert(disposable1) + _ = self.disposables!.insert(disposable2) + _ = self.disposables!.insert(disposable3) + _ = self.disposables!.insert(disposable4) + + for disposable in disposables { + _ = self.disposables!.insert(disposable) + } + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(disposables: [Disposable]) { + for disposable in disposables { + _ = self.disposables!.insert(disposable) + } + } + + /** + Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + + - parameter disposable: Disposable to add. + - returns: Key that can be used to remove disposable from composite disposable. In case dispose bag was already + disposed `nil` will be returned. + */ + public func insert(_ disposable: Disposable) -> DisposeKey? { + let key = self._insert(disposable) + + if key == nil { + disposable.dispose() + } + + return key + } + + private func _insert(_ disposable: Disposable) -> DisposeKey? { + self.lock.performLocked { + let bagKey = self.disposables?.insert(disposable) + return bagKey.map(DisposeKey.init) + } + } + + /// - returns: Gets the number of disposables contained in the `CompositeDisposable`. + public var count: Int { + self.lock.performLocked { self.disposables?.count ?? 0 } + } + + /// Removes and disposes the disposable identified by `disposeKey` from the CompositeDisposable. + /// + /// - parameter disposeKey: Key used to identify disposable to be removed. + public func remove(for disposeKey: DisposeKey) { + self._remove(for: disposeKey)?.dispose() + } + + private func _remove(for disposeKey: DisposeKey) -> Disposable? { + self.lock.performLocked { self.disposables?.removeKey(disposeKey.key) } + } + + /// Disposes all disposables in the group and removes them from the group. + public func dispose() { + if let disposables = self._dispose() { + disposeAll(in: disposables) + } + } + + private func _dispose() -> Bag? { + self.lock.performLocked { + let current = self.disposables + self.disposables = nil + return current + } + } +} + +extension Disposables { + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) -> Cancelable { + CompositeDisposable(disposable1, disposable2, disposable3) + } + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposables: Disposable ...) -> Cancelable { + var disposables = disposables + disposables.append(disposable1) + disposables.append(disposable2) + disposables.append(disposable3) + return CompositeDisposable(disposables: disposables) + } + + /// Creates a disposable with the given disposables. + public static func create(_ disposables: [Disposable]) -> Cancelable { + switch disposables.count { + case 2: + return Disposables.create(disposables[0], disposables[1]) + default: + return CompositeDisposable(disposables: disposables) + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/Disposables.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/Disposables.swift new file mode 100644 index 000000000..8cd6e28c3 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/Disposables.swift @@ -0,0 +1,13 @@ +// +// Disposables.swift +// RxSwift +// +// Created by Mohsen Ramezanpoor on 01/08/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +/// A collection of utility methods for common disposable operations. +public struct Disposables { + private init() {} +} + diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/DisposeBag.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/DisposeBag.swift new file mode 100644 index 000000000..1a673bcce --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/DisposeBag.swift @@ -0,0 +1,144 @@ +// +// DisposeBag.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Disposable { + /// Adds `self` to `bag` + /// + /// - parameter bag: `DisposeBag` to add `self` to. + public func disposed(by bag: DisposeBag) { + bag.insert(self) + } +} + +/** +Thread safe bag that disposes added disposables on `deinit`. + +This returns ARC (RAII) like resource management to `RxSwift`. + +In case contained disposables need to be disposed, just put a different dispose bag +or create a new one in its place. + + self.existingDisposeBag = DisposeBag() + +In case explicit disposal is necessary, there is also `CompositeDisposable`. +*/ +public final class DisposeBag: DisposeBase { + + private var lock = SpinLock() + + // state + private var disposables = [Disposable]() + private var isDisposed = false + + /// Constructs new empty dispose bag. + public override init() { + super.init() + } + + /// Adds `disposable` to be disposed when dispose bag is being deinited. + /// + /// - parameter disposable: Disposable to add. + public func insert(_ disposable: Disposable) { + self._insert(disposable)?.dispose() + } + + private func _insert(_ disposable: Disposable) -> Disposable? { + self.lock.performLocked { + if self.isDisposed { + return disposable + } + + self.disposables.append(disposable) + + return nil + } + } + + /// This is internal on purpose, take a look at `CompositeDisposable` instead. + private func dispose() { + let oldDisposables = self._dispose() + + for disposable in oldDisposables { + disposable.dispose() + } + } + + private func _dispose() -> [Disposable] { + self.lock.performLocked { + let disposables = self.disposables + + self.disposables.removeAll(keepingCapacity: false) + self.isDisposed = true + + return disposables + } + } + + deinit { + self.dispose() + } +} + +extension DisposeBag { + /// Convenience init allows a list of disposables to be gathered for disposal. + public convenience init(disposing disposables: Disposable...) { + self.init() + self.disposables += disposables + } + + /// Convenience init which utilizes a function builder to let you pass in a list of + /// disposables to make a DisposeBag of. + public convenience init(@DisposableBuilder builder: () -> [Disposable]) { + self.init(disposing: builder()) + } + + /// Convenience init allows an array of disposables to be gathered for disposal. + public convenience init(disposing disposables: [Disposable]) { + self.init() + self.disposables += disposables + } + + /// Convenience function allows a list of disposables to be gathered for disposal. + public func insert(_ disposables: Disposable...) { + self.insert(disposables) + } + + /// Convenience function allows a list of disposables to be gathered for disposal. + public func insert(@DisposableBuilder builder: () -> [Disposable]) { + self.insert(builder()) + } + + /// Convenience function allows an array of disposables to be gathered for disposal. + public func insert(_ disposables: [Disposable]) { + self.lock.performLocked { + if self.isDisposed { + disposables.forEach { $0.dispose() } + } else { + self.disposables += disposables + } + } + } + + /// A function builder accepting a list of Disposables and returning them as an array. + #if swift(>=5.4) + @resultBuilder + public struct DisposableBuilder { + public static func buildBlock(_ disposables: Disposable...) -> [Disposable] { + return disposables + } + } + #else + @_functionBuilder + public struct DisposableBuilder { + public static func buildBlock(_ disposables: Disposable...) -> [Disposable] { + return disposables + } + } + #endif + +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/DisposeBase.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/DisposeBase.swift new file mode 100644 index 000000000..0d4b2fb7f --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/DisposeBase.swift @@ -0,0 +1,22 @@ +// +// DisposeBase.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Base class for all disposables. +public class DisposeBase { + init() { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/NopDisposable.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/NopDisposable.swift new file mode 100644 index 000000000..dd436ba9c --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/NopDisposable.swift @@ -0,0 +1,30 @@ +// +// NopDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable that does nothing on disposal. +/// +/// Nop = No Operation +private struct NopDisposable : Disposable { + + fileprivate static let noOp: Disposable = NopDisposable() + + private init() { + + } + + /// Does nothing. + public func dispose() { + } +} + +extension Disposables { + /** + Creates a disposable that does nothing on disposal. + */ + static public func create() -> Disposable { NopDisposable.noOp } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/RefCountDisposable.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/RefCountDisposable.swift new file mode 100644 index 000000000..a59f7789d --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/RefCountDisposable.swift @@ -0,0 +1,112 @@ +// +// RefCountDisposable.swift +// RxSwift +// +// Created by Junior B. on 10/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. +public final class RefCountDisposable : DisposeBase, Cancelable { + private var lock = SpinLock() + private var disposable = nil as Disposable? + private var primaryDisposed = false + private var count = 0 + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + self.lock.performLocked { self.disposable == nil } + } + + /// Initializes a new instance of the `RefCountDisposable`. + public init(disposable: Disposable) { + self.disposable = disposable + super.init() + } + + /** + Holds a dependent disposable that when disposed decreases the refcount on the underlying disposable. + + When getter is called, a dependent disposable contributing to the reference count that manages the underlying disposable's lifetime is returned. + */ + public func retain() -> Disposable { + self.lock.performLocked { + if self.disposable != nil { + do { + _ = try incrementChecked(&self.count) + } catch { + rxFatalError("RefCountDisposable increment failed") + } + + return RefCountInnerDisposable(self) + } else { + return Disposables.create() + } + } + } + + /// Disposes the underlying disposable only when all dependent disposables have been disposed. + public func dispose() { + let oldDisposable: Disposable? = self.lock.performLocked { + if let oldDisposable = self.disposable, !self.primaryDisposed { + self.primaryDisposed = true + + if self.count == 0 { + self.disposable = nil + return oldDisposable + } + } + + return nil + } + + if let disposable = oldDisposable { + disposable.dispose() + } + } + + fileprivate func release() { + let oldDisposable: Disposable? = self.lock.performLocked { + if let oldDisposable = self.disposable { + do { + _ = try decrementChecked(&self.count) + } catch { + rxFatalError("RefCountDisposable decrement on release failed") + } + + guard self.count >= 0 else { + rxFatalError("RefCountDisposable counter is lower than 0") + } + + if self.primaryDisposed && self.count == 0 { + self.disposable = nil + return oldDisposable + } + } + + return nil + } + + if let disposable = oldDisposable { + disposable.dispose() + } + } +} + +internal final class RefCountInnerDisposable: DisposeBase, Disposable +{ + private let parent: RefCountDisposable + private let isDisposed = AtomicInt(0) + + init(_ parent: RefCountDisposable) { + self.parent = parent + super.init() + } + + internal func dispose() + { + if fetchOr(self.isDisposed, 1) == 0 { + self.parent.release() + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/ScheduledDisposable.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/ScheduledDisposable.swift new file mode 100644 index 000000000..2cf997bca --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/ScheduledDisposable.swift @@ -0,0 +1,50 @@ +// +// ScheduledDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +private let disposeScheduledDisposable: (ScheduledDisposable) -> Disposable = { sd in + sd.disposeInner() + return Disposables.create() +} + +/// Represents a disposable resource whose disposal invocation will be scheduled on the specified scheduler. +public final class ScheduledDisposable : Cancelable { + public let scheduler: ImmediateSchedulerType + + private let disposed = AtomicInt(0) + + // state + private var disposable: Disposable? + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + isFlagSet(self.disposed, 1) + } + + /** + Initializes a new instance of the `ScheduledDisposable` that uses a `scheduler` on which to dispose the `disposable`. + + - parameter scheduler: Scheduler where the disposable resource will be disposed on. + - parameter disposable: Disposable resource to dispose on the given scheduler. + */ + public init(scheduler: ImmediateSchedulerType, disposable: Disposable) { + self.scheduler = scheduler + self.disposable = disposable + } + + /// Disposes the wrapped disposable on the provided scheduler. + public func dispose() { + _ = self.scheduler.schedule(self, action: disposeScheduledDisposable) + } + + func disposeInner() { + if fetchOr(self.disposed, 1) == 0 { + self.disposable!.dispose() + self.disposable = nil + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/SerialDisposable.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/SerialDisposable.swift new file mode 100644 index 000000000..ef4690d32 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/SerialDisposable.swift @@ -0,0 +1,73 @@ +// +// SerialDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. +public final class SerialDisposable : DisposeBase, Cancelable { + private var lock = SpinLock() + + // state + private var current = nil as Disposable? + private var disposed = false + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + self.disposed + } + + /// Initializes a new instance of the `SerialDisposable`. + override public init() { + super.init() + } + + /** + Gets or sets the underlying disposable. + + Assigning this property disposes the previous disposable object. + + If the `SerialDisposable` has already been disposed, assignment to this property causes immediate disposal of the given disposable object. + */ + public var disposable: Disposable { + get { + self.lock.performLocked { + self.current ?? Disposables.create() + } + } + set (newDisposable) { + let disposable: Disposable? = self.lock.performLocked { + if self.isDisposed { + return newDisposable + } + else { + let toDispose = self.current + self.current = newDisposable + return toDispose + } + } + + if let disposable = disposable { + disposable.dispose() + } + } + } + + /// Disposes the underlying disposable as well as all future replacements. + public func dispose() { + self._dispose()?.dispose() + } + + private func _dispose() -> Disposable? { + self.lock.performLocked { + guard !self.isDisposed else { return nil } + + self.disposed = true + let current = self.current + self.current = nil + return current + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/SingleAssignmentDisposable.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/SingleAssignmentDisposable.swift new file mode 100644 index 000000000..4a5fb8662 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/SingleAssignmentDisposable.swift @@ -0,0 +1,72 @@ +// +// SingleAssignmentDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + +If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an exception. +*/ +public final class SingleAssignmentDisposable : DisposeBase, Cancelable { + + private struct DisposeState: OptionSet { + let rawValue: Int32 + + static let disposed = DisposeState(rawValue: 1 << 0) + static let disposableSet = DisposeState(rawValue: 1 << 1) + } + + // state + private let state = AtomicInt(0) + private var disposable = nil as Disposable? + + /// - returns: A value that indicates whether the object is disposed. + public var isDisposed: Bool { + isFlagSet(self.state, DisposeState.disposed.rawValue) + } + + /// Initializes a new instance of the `SingleAssignmentDisposable`. + public override init() { + super.init() + } + + /// Gets or sets the underlying disposable. After disposal, the result of getting this property is undefined. + /// + /// **Throws exception if the `SingleAssignmentDisposable` has already been assigned to.** + public func setDisposable(_ disposable: Disposable) { + self.disposable = disposable + + let previousState = fetchOr(self.state, DisposeState.disposableSet.rawValue) + + if (previousState & DisposeState.disposableSet.rawValue) != 0 { + rxFatalError("oldState.disposable != nil") + } + + if (previousState & DisposeState.disposed.rawValue) != 0 { + disposable.dispose() + self.disposable = nil + } + } + + /// Disposes the underlying disposable. + public func dispose() { + let previousState = fetchOr(self.state, DisposeState.disposed.rawValue) + + if (previousState & DisposeState.disposed.rawValue) != 0 { + return + } + + if (previousState & DisposeState.disposableSet.rawValue) != 0 { + guard let disposable = self.disposable else { + rxFatalError("Disposable not set") + } + disposable.dispose() + self.disposable = nil + } + } + +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/SubscriptionDisposable.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/SubscriptionDisposable.swift new file mode 100644 index 000000000..a406c84cb --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Disposables/SubscriptionDisposable.swift @@ -0,0 +1,21 @@ +// +// SubscriptionDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct SubscriptionDisposable : Disposable { + private let key: T.DisposeKey + private weak var owner: T? + + init(owner: T, key: T.DisposeKey) { + self.owner = owner + self.key = key + } + + func dispose() { + self.owner?.synchronizedUnsubscribe(self.key) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Errors.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Errors.swift new file mode 100644 index 000000000..d2d2917e7 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Errors.swift @@ -0,0 +1,52 @@ +// +// Errors.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +let RxErrorDomain = "RxErrorDomain" +let RxCompositeFailures = "RxCompositeFailures" + +/// Generic Rx error codes. +public enum RxError + : Swift.Error + , CustomDebugStringConvertible { + /// Unknown error occurred. + case unknown + /// Performing an action on disposed object. + case disposed(object: AnyObject) + /// Arithmetic overflow error. + case overflow + /// Argument out of range error. + case argumentOutOfRange + /// Sequence doesn't contain any elements. + case noElements + /// Sequence contains more than one element. + case moreThanOneElement + /// Timeout error. + case timeout +} + +extension RxError { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + switch self { + case .unknown: + return "Unknown error occurred." + case .disposed(let object): + return "Object `\(object)` was already disposed." + case .overflow: + return "Arithmetic overflow occurred." + case .argumentOutOfRange: + return "Argument out of range." + case .noElements: + return "Sequence doesn't contain any elements." + case .moreThanOneElement: + return "Sequence contains more than one element." + case .timeout: + return "Sequence timeout." + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Event.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Event.swift new file mode 100644 index 000000000..01861a858 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Event.swift @@ -0,0 +1,104 @@ +// +// Event.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a sequence event. +/// +/// Sequence grammar: +/// **next\* (error | completed)** +@frozen public enum Event { + /// Next element is produced. + case next(Element) + + /// Sequence terminated with an error. + case error(Swift.Error) + + /// Sequence completed successfully. + case completed +} + +extension Event: CustomDebugStringConvertible { + /// Description of event. + public var debugDescription: String { + switch self { + case .next(let value): + return "next(\(value))" + case .error(let error): + return "error(\(error))" + case .completed: + return "completed" + } + } +} + +extension Event { + /// Is `completed` or `error` event. + public var isStopEvent: Bool { + switch self { + case .next: return false + case .error, .completed: return true + } + } + + /// If `next` event, returns element value. + public var element: Element? { + if case .next(let value) = self { + return value + } + return nil + } + + /// If `error` event, returns error. + public var error: Swift.Error? { + if case .error(let error) = self { + return error + } + return nil + } + + /// If `completed` event, returns `true`. + public var isCompleted: Bool { + if case .completed = self { + return true + } + return false + } +} + +extension Event { + /// Maps sequence elements using transform. If error happens during the transform, `.error` + /// will be returned as value. + public func map(_ transform: (Element) throws -> Result) -> Event { + do { + switch self { + case let .next(element): + return .next(try transform(element)) + case let .error(error): + return .error(error) + case .completed: + return .completed + } + } + catch let e { + return .error(e) + } + } +} + +/// A type that can be converted to `Event`. +public protocol EventConvertible { + /// Type of element in event + associatedtype Element + + /// Event representation of this instance + var event: Event { get } +} + +extension Event: EventConvertible { + /// Event representation of this instance + public var event: Event { self } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Extensions/Bag+Rx.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Extensions/Bag+Rx.swift new file mode 100644 index 000000000..97946837a --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Extensions/Bag+Rx.swift @@ -0,0 +1,50 @@ +// +// Bag+Rx.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/19/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + + +// MARK: forEach + +@inline(__always) +func dispatch(_ bag: Bag<(Event) -> Void>, _ event: Event) { + bag._value0?(event) + + if bag._onlyFastPath { + return + } + + let pairs = bag._pairs + for i in 0 ..< pairs.count { + pairs[i].value(event) + } + + if let dictionary = bag._dictionary { + for element in dictionary.values { + element(event) + } + } +} + +/// Dispatches `dispose` to all disposables contained inside bag. +func disposeAll(in bag: Bag) { + bag._value0?.dispose() + + if bag._onlyFastPath { + return + } + + let pairs = bag._pairs + for i in 0 ..< pairs.count { + pairs[i].value.dispose() + } + + if let dictionary = bag._dictionary { + for element in dictionary.values { + element.dispose() + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/GroupedObservable.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/GroupedObservable.swift new file mode 100644 index 000000000..189a8c46a --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/GroupedObservable.swift @@ -0,0 +1,35 @@ +// +// GroupedObservable.swift +// RxSwift +// +// Created by Tomi Koskinen on 01/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an observable sequence of elements that have a common key. +public struct GroupedObservable : ObservableType { + /// Gets the common key. + public let key: Key + + private let source: Observable + + /// Initializes grouped observable sequence with key and source observable sequence. + /// + /// - parameter key: Grouped observable sequence key + /// - parameter source: Observable sequence that represents sequence of elements for the key + /// - returns: Grouped observable sequence of elements for the specific key + public init(key: Key, source: Observable) { + self.key = key + self.source = source + } + + /// Subscribes `observer` to receive events for this sequence. + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.source.subscribe(observer) + } + + /// Converts `self` to `Observable` sequence. + public func asObservable() -> Observable { + self.source + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/ImmediateSchedulerType.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/ImmediateSchedulerType.swift new file mode 100644 index 000000000..954fbf04b --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/ImmediateSchedulerType.swift @@ -0,0 +1,36 @@ +// +// ImmediateSchedulerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an object that immediately schedules units of work. +public protocol ImmediateSchedulerType { + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable +} + +extension ImmediateSchedulerType { + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRecursive(_ state: State, action: @escaping (_ state: State, _ recurse: (State) -> Void) -> Void) -> Disposable { + let recursiveScheduler = RecursiveImmediateScheduler(action: action, scheduler: self) + + recursiveScheduler.schedule(state) + + return Disposables.create(with: recursiveScheduler.dispose) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observable+Concurrency.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observable+Concurrency.swift new file mode 100644 index 000000000..45ad05ede --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observable+Concurrency.swift @@ -0,0 +1,79 @@ +// +// Observable+Concurrency.swift +// RxSwift +// +// Created by Shai Mishali on 22/09/2021. +// Copyright © 2021 Krunoslav Zaher. All rights reserved. +// + +#if swift(>=5.6) && canImport(_Concurrency) +import Foundation + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public extension ObservableConvertibleType { + /// Allows iterating over the values of an Observable + /// asynchronously via Swift's concurrency features (`async/await`) + /// + /// A sample usage would look like so: + /// + /// ```swift + /// do { + /// for try await value in observable.values { + /// // Handle emitted values + /// } + /// } catch { + /// // Handle error + /// } + /// ``` + var values: AsyncThrowingStream { + AsyncThrowingStream { continuation in + var isFinished = false + let disposable = asObservable().subscribe( + onNext: { value in continuation.yield(value) }, + onError: { error in + isFinished = true + continuation.finish(throwing: error) + }, + onCompleted: { + isFinished = true + continuation.finish() + }, + onDisposed: { + guard !isFinished else { return } + continuation.finish(throwing: CancellationError() ) + } + ) + continuation.onTermination = { @Sendable termination in + if case .cancelled = termination { + disposable.dispose() + } + } + } + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public extension AsyncSequence { + /// Convert an `AsyncSequence` to an `Observable` emitting + /// values of the asynchronous sequence's type + /// + /// - returns: An `Observable` of the async sequence's type + func asObservable() -> Observable { + Observable.create { observer in + let task = Task { + do { + for try await value in self { + observer.onNext(value) + } + + observer.onCompleted() + } catch { + observer.onError(error) + } + } + + return Disposables.create { task.cancel() } + } + } +} +#endif diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observable.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observable.swift new file mode 100644 index 000000000..93a3ed78f --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observable.swift @@ -0,0 +1,31 @@ +// +// Observable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// A type-erased `ObservableType`. +/// +/// It represents a push style sequence. +public class Observable : ObservableType { + init() { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + rxAbstractMethod() + } + + public func asObservable() -> Observable { self } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} + diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/ObservableConvertibleType.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/ObservableConvertibleType.swift new file mode 100644 index 000000000..0f56a8165 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/ObservableConvertibleType.swift @@ -0,0 +1,18 @@ +// +// ObservableConvertibleType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Type that can be converted to observable sequence (`Observable`). +public protocol ObservableConvertibleType { + /// Type of elements in sequence. + associatedtype Element + + /// Converts `self` to `Observable` sequence. + /// + /// - returns: Observable sequence that represents `self`. + func asObservable() -> Observable +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/ObservableType+Extensions.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/ObservableType+Extensions.swift new file mode 100644 index 000000000..ac850c3ba --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/ObservableType+Extensions.swift @@ -0,0 +1,174 @@ +// +// ObservableType+Extensions.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if DEBUG + import Foundation +#endif + +extension ObservableType { + /** + Subscribes an event handler to an observable sequence. + + - parameter on: Action to invoke for each event in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func subscribe(_ on: @escaping (Event) -> Void) -> Disposable { + let observer = AnonymousObserver { e in + on(e) + } + return self.asObservable().subscribe(observer) + } + + /** + Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence. + + Also, take in an object and provide an unretained, safe to use (i.e. not implicitly unwrapped), reference to it along with the events emitted by the sequence. + + - Note: If `object` can't be retained, none of the other closures will be invoked. + + - parameter object: The object to provide an unretained reference on. + - 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. + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription). + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func subscribe( + with object: Object, + onNext: ((Object, Element) -> Void)? = nil, + onError: ((Object, Swift.Error) -> Void)? = nil, + onCompleted: ((Object) -> Void)? = nil, + onDisposed: ((Object) -> Void)? = nil + ) -> Disposable { + subscribe( + onNext: { [weak object] in + guard let object = object else { return } + onNext?(object, $0) + }, + onError: { [weak object] in + guard let object = object else { return } + onError?(object, $0) + }, + onCompleted: { [weak object] in + guard let object = object else { return } + onCompleted?(object) + }, + onDisposed: { [weak object] in + guard let object = object else { return } + onDisposed?(object) + } + ) + } + + /** + Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable 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. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription). + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func subscribe( + onNext: ((Element) -> Void)? = nil, + onError: ((Swift.Error) -> Void)? = nil, + onCompleted: (() -> Void)? = nil, + onDisposed: (() -> Void)? = nil + ) -> Disposable { + let disposable: Disposable + + if let disposed = onDisposed { + disposable = Disposables.create(with: disposed) + } + else { + disposable = Disposables.create() + } + + #if DEBUG + let synchronizationTracker = SynchronizationTracker() + #endif + + let callStack = Hooks.recordCallStackOnError ? Hooks.customCaptureSubscriptionCallstack() : [] + + let observer = AnonymousObserver { event in + + #if DEBUG + synchronizationTracker.register(synchronizationErrorMessage: .default) + defer { synchronizationTracker.unregister() } + #endif + + switch event { + case .next(let value): + onNext?(value) + case .error(let error): + if let onError = onError { + onError(error) + } + else { + Hooks.defaultErrorHandler(callStack, error) + } + disposable.dispose() + case .completed: + onCompleted?() + disposable.dispose() + } + } + return Disposables.create( + self.asObservable().subscribe(observer), + disposable + ) + } +} + +import Foundation + +extension Hooks { + public typealias DefaultErrorHandler = (_ subscriptionCallStack: [String], _ error: Error) -> Void + public typealias CustomCaptureSubscriptionCallstack = () -> [String] + + private static let lock = RecursiveLock() + private static var _defaultErrorHandler: DefaultErrorHandler = { subscriptionCallStack, error in + #if DEBUG + let serializedCallStack = subscriptionCallStack.joined(separator: "\n") + print("Unhandled error happened: \(error)") + if !serializedCallStack.isEmpty { + print("subscription called from:\n\(serializedCallStack)") + } + #endif + } + private static var _customCaptureSubscriptionCallstack: CustomCaptureSubscriptionCallstack = { + #if DEBUG + return Thread.callStackSymbols + #else + return [] + #endif + } + + /// Error handler called in case onError handler wasn't provided. + public static var defaultErrorHandler: DefaultErrorHandler { + get { + lock.performLocked { _defaultErrorHandler } + } + set { + lock.performLocked { _defaultErrorHandler = newValue } + } + } + + /// Subscription callstack block to fetch custom callstack information. + public static var customCaptureSubscriptionCallstack: CustomCaptureSubscriptionCallstack { + get { + lock.performLocked { _customCaptureSubscriptionCallstack } + } + set { + lock.performLocked { _customCaptureSubscriptionCallstack = newValue } + } + } +} + diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/ObservableType.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/ObservableType.swift new file mode 100644 index 000000000..279bf7f46 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/ObservableType.swift @@ -0,0 +1,45 @@ +// +// ObservableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a push style sequence. +public protocol ObservableType: ObservableConvertibleType { + /** + Subscribes `observer` to receive events for this sequence. + + ### Grammar + + **Next\* (Error | Completed)?** + + * sequences can produce zero or more elements so zero or more `Next` events can be sent to `observer` + * once an `Error` or `Completed` event is sent, the sequence terminates and can't produce any other elements + + It is possible that events are sent from different threads, but no two events can be sent concurrently to + `observer`. + + ### Resource Management + + When sequence sends `Complete` or `Error` event all internal resources that compute sequence elements + will be freed. + + To cancel production of sequence elements and free resources immediately, call `dispose` on returned + subscription. + + - returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources. + */ + func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element +} + +extension ObservableType { + + /// Default implementation of converting `ObservableType` to `Observable`. + public func asObservable() -> Observable { + // temporary workaround + //return Observable.create(subscribe: self.subscribe) + Observable.create { o in self.subscribe(o) } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/AddRef.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/AddRef.swift new file mode 100644 index 000000000..a96dfcb03 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/AddRef.swift @@ -0,0 +1,44 @@ +// +// AddRef.swift +// RxSwift +// +// Created by Junior B. on 30/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +final class AddRefSink : Sink, ObserverType { + typealias Element = Observer.Element + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .completed, .error: + self.forwardOn(event) + self.dispose() + } + } +} + +final class AddRef : Producer { + + private let source: Observable + private let refCount: RefCountDisposable + + init(source: Observable, refCount: RefCountDisposable) { + self.source = source + self.refCount = refCount + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let releaseDisposable = self.refCount.retain() + let sink = AddRefSink(observer: observer, cancel: cancel) + let subscription = Disposables.create(releaseDisposable, self.source.subscribe(sink)) + + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Amb.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Amb.swift new file mode 100644 index 000000000..efc17a8d9 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Amb.swift @@ -0,0 +1,157 @@ +// +// Amb.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Propagates the observable sequence that reacts first. + + - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) + + - returns: An observable sequence that surfaces any of the given sequences, whichever reacted first. + */ + public static func amb(_ sequence: Sequence) -> Observable + where Sequence.Element == Observable { + sequence.reduce(Observable.never()) { a, o in + a.amb(o.asObservable()) + } + } +} + +extension ObservableType { + + /** + Propagates the observable sequence that reacts first. + + - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) + + - parameter right: Second observable sequence. + - returns: An observable sequence that surfaces either of the given sequences, whichever reacted first. + */ + public func amb + (_ right: O2) + -> Observable where O2.Element == Element { + Amb(left: self.asObservable(), right: right.asObservable()) + } +} + +private enum AmbState { + case neither + case left + case right +} + +final private class AmbObserver: ObserverType { + typealias Element = Observer.Element + typealias Parent = AmbSink + typealias This = AmbObserver + typealias Sink = (This, Event) -> Void + + private let parent: Parent + fileprivate var sink: Sink + fileprivate var cancel: Disposable + + init(parent: Parent, cancel: Disposable, sink: @escaping Sink) { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + + self.parent = parent + self.sink = sink + self.cancel = cancel + } + + func on(_ event: Event) { + self.sink(self, event) + if event.isStopEvent { + self.cancel.dispose() + } + } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} + +final private class AmbSink: Sink { + typealias Element = Observer.Element + typealias Parent = Amb + typealias AmbObserverType = AmbObserver + + private let parent: Parent + + private let lock = RecursiveLock() + // state + private var choice = AmbState.neither + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let disposeAll = Disposables.create(subscription1, subscription2) + + let forwardEvent = { (o: AmbObserverType, event: Event) -> Void in + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + + let decide = { (o: AmbObserverType, event: Event, me: AmbState, otherSubscription: Disposable) in + self.lock.performLocked { + if self.choice == .neither { + self.choice = me + o.sink = forwardEvent + o.cancel = disposeAll + otherSubscription.dispose() + } + + if self.choice == me { + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + } + } + + let sink1 = AmbObserver(parent: self, cancel: subscription1) { o, e in + decide(o, e, .left, subscription2) + } + + let sink2 = AmbObserver(parent: self, cancel: subscription1) { o, e in + decide(o, e, .right, subscription1) + } + + subscription1.setDisposable(self.parent.left.subscribe(sink1)) + subscription2.setDisposable(self.parent.right.subscribe(sink2)) + + return disposeAll + } +} + +final private class Amb: Producer { + fileprivate let left: Observable + fileprivate let right: Observable + + init(left: Observable, right: Observable) { + self.left = left + self.right = right + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = AmbSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/AsMaybe.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/AsMaybe.swift new file mode 100644 index 000000000..6fa625784 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/AsMaybe.swift @@ -0,0 +1,48 @@ +// +// AsMaybe.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +private final class AsMaybeSink : Sink, ObserverType { + typealias Element = Observer.Element + + private var element: Event? + + func on(_ event: Event) { + switch event { + case .next: + if self.element != nil { + self.forwardOn(.error(RxError.moreThanOneElement)) + self.dispose() + } + + self.element = event + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if let element = self.element { + self.forwardOn(element) + } + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class AsMaybe: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = AsMaybeSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/AsSingle.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/AsSingle.swift new file mode 100644 index 000000000..b39932f12 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/AsSingle.swift @@ -0,0 +1,51 @@ +// +// AsSingle.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +private final class AsSingleSink : Sink, ObserverType { + typealias Element = Observer.Element + + private var element: Event? + + func on(_ event: Event) { + switch event { + case .next: + if self.element != nil { + self.forwardOn(.error(RxError.moreThanOneElement)) + self.dispose() + } + + self.element = event + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if let element = self.element { + self.forwardOn(element) + self.forwardOn(.completed) + } + else { + self.forwardOn(.error(RxError.noElements)) + } + self.dispose() + } + } +} + +final class AsSingle: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = AsSingleSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Buffer.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Buffer.swift new file mode 100644 index 000000000..087c4cf57 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Buffer.swift @@ -0,0 +1,138 @@ +// +// Buffer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers. + + A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first. + + - seealso: [buffer operator on reactivex.io](http://reactivex.io/documentation/operators/buffer.html) + + - parameter timeSpan: Maximum time length of a buffer. + - parameter count: Maximum element count of a buffer. + - parameter scheduler: Scheduler to run buffering timers on. + - returns: An observable sequence of buffers. + */ + public func buffer(timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) + -> Observable<[Element]> { + BufferTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) + } +} + +final private class BufferTimeCount: Producer<[Element]> { + + fileprivate let timeSpan: RxTimeInterval + fileprivate let count: Int + fileprivate let scheduler: SchedulerType + fileprivate let source: Observable + + init(source: Observable, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { + self.source = source + self.timeSpan = timeSpan + self.count = count + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == [Element] { + let sink = BufferTimeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class BufferTimeCountSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType where Observer.Element == [Element] { + typealias Parent = BufferTimeCount + + private let parent: Parent + + let lock = RecursiveLock() + + // state + private let timerD = SerialDisposable() + private var buffer = [Element]() + private var windowID = 0 + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + self.createTimer(self.windowID) + return Disposables.create(timerD, parent.source.subscribe(self)) + } + + func startNewWindowAndSendCurrentOne() { + self.windowID = self.windowID &+ 1 + let windowID = self.windowID + + let buffer = self.buffer + self.buffer = [] + self.forwardOn(.next(buffer)) + + self.createTimer(windowID) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let element): + self.buffer.append(element) + + if self.buffer.count == self.parent.count { + self.startNewWindowAndSendCurrentOne() + } + + case .error(let error): + self.buffer = [] + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.next(self.buffer)) + self.forwardOn(.completed) + self.dispose() + } + } + + func createTimer(_ windowID: Int) { + if self.timerD.isDisposed { + return + } + + if self.windowID != windowID { + return + } + + let nextTimer = SingleAssignmentDisposable() + + self.timerD.disposable = nextTimer + + let disposable = self.parent.scheduler.scheduleRelative(windowID, dueTime: self.parent.timeSpan) { previousWindowID in + self.lock.performLocked { + if previousWindowID != self.windowID { + return + } + + self.startNewWindowAndSendCurrentOne() + } + + return Disposables.create() + } + + nextTimer.setDisposable(disposable) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Catch.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Catch.swift new file mode 100644 index 000000000..2efd66062 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Catch.swift @@ -0,0 +1,275 @@ +// +// Catch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter handler: Error handler function, producing another observable sequence. + - 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. + */ + public func `catch`(_ handler: @escaping (Swift.Error) throws -> Observable) + -> Observable { + Catch(source: self.asObservable(), handler: handler) + } + + /** + Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter handler: Error handler function, producing another observable sequence. + - 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. + */ + @available(*, deprecated, renamed: "catch(_:)") + public func catchError(_ handler: @escaping (Swift.Error) throws -> Observable) + -> Observable { + `catch`(handler) + } + + /** + Continues an observable sequence that is terminated by an error with a single element. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter element: Last element in an observable sequence in case error occurs. + - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. + */ + public func catchAndReturn(_ element: Element) + -> Observable { + Catch(source: self.asObservable(), handler: { _ in Observable.just(element) }) + } + + /** + Continues an observable sequence that is terminated by an error with a single element. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter element: Last element in an observable sequence in case error occurs. + - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. + */ + @available(*, deprecated, renamed: "catchAndReturn(_:)") + public func catchErrorJustReturn(_ element: Element) + -> Observable { + catchAndReturn(element) + } +} + +extension ObservableType { + /** + Continues an observable sequence that is terminated by an error with the next observable sequence. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - returns: An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. + */ + @available(*, deprecated, renamed: "catch(onSuccess:onFailure:onDisposed:)") + public static func catchError(_ sequence: Sequence) -> Observable + where Sequence.Element == Observable { + `catch`(sequence: sequence) + } + + /** + Continues an observable sequence that is terminated by an error with the next observable sequence. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - returns: An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. + */ + public static func `catch`(sequence: Sequence) -> Observable + where Sequence.Element == Observable { + CatchSequence(sources: sequence) + } +} + +extension ObservableType { + + /** + Repeats the source observable sequence until it successfully terminates. + + **This could potentially create an infinite sequence.** + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - returns: Observable sequence to repeat until it successfully terminates. + */ + public func retry() -> Observable { + CatchSequence(sources: InfiniteSequence(repeatedValue: self.asObservable())) + } + + /** + Repeats the source observable sequence the specified number of times in case of an error or until it successfully terminates. + + If you encounter an error and want it to retry once, then you must use `retry(2)` + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter maxAttemptCount: Maximum number of times to repeat the sequence. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + public func retry(_ maxAttemptCount: Int) + -> Observable { + CatchSequence(sources: Swift.repeatElement(self.asObservable(), count: maxAttemptCount)) + } +} + +// catch with callback + +final private class CatchSinkProxy: ObserverType { + typealias Element = Observer.Element + typealias Parent = CatchSink + + private let parent: Parent + + init(parent: Parent) { + self.parent = parent + } + + func on(_ event: Event) { + self.parent.forwardOn(event) + + switch event { + case .next: + break + case .error, .completed: + self.parent.dispose() + } + } +} + +final private class CatchSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = Catch + + private let parent: Parent + private let subscription = SerialDisposable() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let d1 = SingleAssignmentDisposable() + self.subscription.disposable = d1 + d1.setDisposable(self.parent.source.subscribe(self)) + + return self.subscription + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .completed: + self.forwardOn(event) + self.dispose() + case .error(let error): + do { + let catchSequence = try self.parent.handler(error) + + let observer = CatchSinkProxy(parent: self) + + self.subscription.disposable = catchSequence.subscribe(observer) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + } +} + +final private class Catch: Producer { + typealias Handler = (Swift.Error) throws -> Observable + + fileprivate let source: Observable + fileprivate let handler: Handler + + init(source: Observable, handler: @escaping Handler) { + self.source = source + self.handler = handler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = CatchSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +// catch enumerable + +final private class CatchSequenceSink + : TailRecursiveSink + , ObserverType where Sequence.Element: ObservableConvertibleType, Sequence.Element.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = CatchSequence + + private var lastError: Swift.Error? + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .error(let error): + self.lastError = error + self.schedule(.moveNext) + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + override func subscribeToNext(_ source: Observable) -> Disposable { + source.subscribe(self) + } + + override func done() { + if let lastError = self.lastError { + self.forwardOn(.error(lastError)) + } + else { + self.forwardOn(.completed) + } + + self.dispose() + } + + override func extract(_ observable: Observable) -> SequenceGenerator? { + if let onError = observable as? CatchSequence { + return (onError.sources.makeIterator(), nil) + } + else { + return nil + } + } +} + +final private class CatchSequence: Producer where Sequence.Element: ObservableConvertibleType { + typealias Element = Sequence.Element.Element + + let sources: Sequence + + init(sources: Sequence) { + self.sources = sources + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = CatchSequenceSink(observer: observer, cancel: cancel) + let subscription = sink.run((self.sources.makeIterator(), nil)) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CombineLatest+Collection.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CombineLatest+Collection.swift new file mode 100644 index 000000000..b56d050bb --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CombineLatest+Collection.swift @@ -0,0 +1,165 @@ +// +// CombineLatest+Collection.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest(_ collection: Collection, resultSelector: @escaping ([Collection.Element.Element]) throws -> Element) -> Observable + where Collection.Element: ObservableType { + CombineLatestCollectionType(sources: collection, resultSelector: resultSelector) + } + + /** + Merges the specified observable sequences into one observable sequence whenever any of the observable sequences produces an element. + + - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest(_ collection: Collection) -> Observable<[Element]> + where Collection.Element: ObservableType, Collection.Element.Element == Element { + CombineLatestCollectionType(sources: collection, resultSelector: { $0 }) + } +} + +final class CombineLatestCollectionTypeSink + : Sink where Collection.Element: ObservableConvertibleType { + typealias Result = Observer.Element + typealias Parent = CombineLatestCollectionType + typealias SourceElement = Collection.Element.Element + + let parent: Parent + + let lock = RecursiveLock() + + // state + var numberOfValues = 0 + var values: [SourceElement?] + var isDone: [Bool] + var numberOfDone = 0 + var subscriptions: [SingleAssignmentDisposable] + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.values = [SourceElement?](repeating: nil, count: parent.count) + self.isDone = [Bool](repeating: false, count: parent.count) + self.subscriptions = [SingleAssignmentDisposable]() + self.subscriptions.reserveCapacity(parent.count) + + for _ in 0 ..< parent.count { + self.subscriptions.append(SingleAssignmentDisposable()) + } + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event, atIndex: Int) { + self.lock.lock(); defer { self.lock.unlock() } + switch event { + case .next(let element): + if self.values[atIndex] == nil { + self.numberOfValues += 1 + } + + self.values[atIndex] = element + + if self.numberOfValues < self.parent.count { + let numberOfOthersThatAreDone = self.numberOfDone - (self.isDone[atIndex] ? 1 : 0) + if numberOfOthersThatAreDone == self.parent.count - 1 { + self.forwardOn(.completed) + self.dispose() + } + return + } + + do { + let result = try self.parent.resultSelector(self.values.map { $0! }) + self.forwardOn(.next(result)) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + if self.isDone[atIndex] { + return + } + + self.isDone[atIndex] = true + self.numberOfDone += 1 + + if self.numberOfDone == self.parent.count { + self.forwardOn(.completed) + self.dispose() + } + else { + self.subscriptions[atIndex].dispose() + } + } + } + + func run() -> Disposable { + var j = 0 + for i in self.parent.sources { + let index = j + let source = i.asObservable() + let disposable = source.subscribe(AnyObserver { event in + self.on(event, atIndex: index) + }) + + self.subscriptions[j].setDisposable(disposable) + + j += 1 + } + + if self.parent.sources.isEmpty { + do { + let result = try self.parent.resultSelector([]) + self.forwardOn(.next(result)) + self.forwardOn(.completed) + self.dispose() + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + } + + return Disposables.create(subscriptions) + } +} + +final class CombineLatestCollectionType: Producer where Collection.Element: ObservableConvertibleType { + typealias ResultSelector = ([Collection.Element.Element]) throws -> Result + + let sources: Collection + let resultSelector: ResultSelector + let count: Int + + init(sources: Collection, resultSelector: @escaping ResultSelector) { + self.sources = sources + self.resultSelector = resultSelector + self.count = self.sources.count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestCollectionTypeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CombineLatest+arity.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CombineLatest+arity.swift new file mode 100644 index 000000000..e69bbab4a --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CombineLatest+arity.swift @@ -0,0 +1,843 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// CombineLatest+arity.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + + +// 2 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.Element, O2.Element) throws -> Element) + -> Observable { + return CombineLatest2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2) + -> Observable<(O1.Element, O2.Element)> { + return CombineLatest2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: { ($0, $1) } + ) + } +} + +final class CombineLatestSink2_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest2 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 2, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + + return Disposables.create([ + subscription1, + subscription2 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2) + } +} + +final class CombineLatest2 : Producer { + typealias ResultSelector = (E1, E2) throws -> Result + + let source1: Observable + let source2: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink2_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 3 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.Element, O2.Element, O3.Element) throws -> Element) + -> Observable { + return CombineLatest3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3) + -> Observable<(O1.Element, O2.Element, O3.Element)> { + return CombineLatest3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: { ($0, $1, $2) } + ) + } +} + +final class CombineLatestSink3_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest3 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 3, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3) + } +} + +final class CombineLatest3 : Producer { + typealias ResultSelector = (E1, E2, E3) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink3_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 4 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element) throws -> Element) + -> Observable { + return CombineLatest4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element)> { + return CombineLatest4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: { ($0, $1, $2, $3) } + ) + } +} + +final class CombineLatestSink4_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest4 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 4, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4) + } +} + +final class CombineLatest4 : Producer { + typealias ResultSelector = (E1, E2, E3, E4) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink4_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 5 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element) throws -> Element) + -> Observable { + return CombineLatest5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element)> { + return CombineLatest5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4) } + ) + } +} + +final class CombineLatestSink5_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest5 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + var latestElement5: E5! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 5, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self.lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self.latestElement5 = e }, this: subscription5) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4, self.latestElement5) + } +} + +final class CombineLatest5 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink5_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 6 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element) throws -> Element) + -> Observable { + return CombineLatest6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element)> { + return CombineLatest6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5) } + ) + } +} + +final class CombineLatestSink6_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest6 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + var latestElement5: E5! = nil + var latestElement6: E6! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 6, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self.lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self.latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: self.lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self.latestElement6 = e }, this: subscription6) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4, self.latestElement5, self.latestElement6) + } +} + +final class CombineLatest6 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink6_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 7 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element) throws -> Element) + -> Observable { + return CombineLatest7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element)> { + return CombineLatest7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6) } + ) + } +} + +final class CombineLatestSink7_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest7 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + var latestElement5: E5! = nil + var latestElement6: E6! = nil + var latestElement7: E7! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 7, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self.lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self.latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: self.lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self.latestElement6 = e }, this: subscription6) + let observer7 = CombineLatestObserver(lock: self.lock, parent: self, index: 6, setLatestValue: { (e: E7) -> Void in self.latestElement7 = e }, this: subscription7) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + subscription7.setDisposable(self.parent.source7.subscribe(observer7)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4, self.latestElement5, self.latestElement6, self.latestElement7) + } +} + +final class CombineLatest7 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink7_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 8 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element) throws -> Element) + -> Observable { + return CombineLatest8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element)> { + return CombineLatest8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6, $7) } + ) + } +} + +final class CombineLatestSink8_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest8 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + var latestElement5: E5! = nil + var latestElement6: E6! = nil + var latestElement7: E7! = nil + var latestElement8: E8! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 8, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + let subscription8 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self.lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self.latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: self.lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self.latestElement6 = e }, this: subscription6) + let observer7 = CombineLatestObserver(lock: self.lock, parent: self, index: 6, setLatestValue: { (e: E7) -> Void in self.latestElement7 = e }, this: subscription7) + let observer8 = CombineLatestObserver(lock: self.lock, parent: self, index: 7, setLatestValue: { (e: E8) -> Void in self.latestElement8 = e }, this: subscription8) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + subscription7.setDisposable(self.parent.source7.subscribe(observer7)) + subscription8.setDisposable(self.parent.source8.subscribe(observer8)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7, + subscription8 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4, self.latestElement5, self.latestElement6, self.latestElement7, self.latestElement8) + } +} + +final class CombineLatest8 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + let source8: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, source8: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + self.source8 = source8 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink8_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CombineLatest+arity.tt b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CombineLatest+arity.tt new file mode 100644 index 000000000..86d8e4b9c --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CombineLatest+arity.tt @@ -0,0 +1,112 @@ +// +// CombineLatest+arity.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +<% for i in 2 ... 8 { %> + +// <%= i %> + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest<<%= (Array(1...i).map { "O\($0): ObservableType" }).joined(separator: ", ") %>> + (<%= (Array(1...i).map { "_ source\($0): O\($0)" }).joined(separator: ", ") %>, resultSelector: @escaping (<%= (Array(1...i).map { "O\($0).Element" }).joined(separator: ", ") %>) throws -> Element) + -> Observable { + return CombineLatest<%= i %>( + <%= (Array(1...i).map { "source\($0): source\($0).asObservable()" }).joined(separator: ", ") %>, + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest<<%= (Array(1...i).map { "O\($0): ObservableType" }).joined(separator: ", ") %>> + (<%= (Array(1...i).map { "_ source\($0): O\($0)" }).joined(separator: ", ") %>) + -> Observable<(<%= (Array(1...i).map { "O\($0).Element" }).joined(separator: ", ") %>)> { + return CombineLatest<%= i %>( + <%= (Array(1...i).map { "source\($0): source\($0).asObservable()" }).joined(separator: ", ") %>, + resultSelector: { (<%= (Array(0..) } + ) + } +} + +final class CombineLatestSink<%= i %>_<<%= (Array(1...i).map { "E\($0)" }).joined(separator: ", ") %>, Observer: ObserverType> : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest<%= i %><<%= (Array(1...i).map { "E\($0)" }).joined(separator: ", ") %>, Result> + + let parent: Parent + +<%= (Array(1...i).map { +" var latestElement\($0): E\($0)! = nil" +}).joined(separator: "\n") %> + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: <%= i %>, observer: observer, cancel: cancel) + } + + func run() -> Disposable { +<%= (Array(1...i).map { +" let subscription\($0) = SingleAssignmentDisposable()" +}).joined(separator: "\n") %> + +<%= (Array(1...i).map { +" let observer\($0) = CombineLatestObserver(lock: self.lock, parent: self, index: \($0 - 1), setLatestValue: { (e: E\($0)) -> Void in self.latestElement\($0) = e }, this: subscription\($0))" +}).joined(separator: "\n") %> + +<%= (Array(1...i).map { +" subscription\($0).setDisposable(self.parent.source\($0).subscribe(observer\($0)))" +}).joined(separator: "\n") %> + + return Disposables.create([ +<%= (Array(1...i).map { " subscription\($0)" }).joined(separator: ",\n") %> + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(<%= (Array(1...i).map { "self.latestElement\($0)" }).joined(separator: ", ") %>) + } +} + +final class CombineLatest<%= i %><<%= (Array(1...i).map { "E\($0)" }).joined(separator: ", ") %>, Result> : Producer { + typealias ResultSelector = (<%= (Array(1...i).map { "E\($0)" }).joined(separator: ", ") %>) throws -> Result + +<%= (Array(1...i).map { +" let source\($0): Observable" +}).joined(separator: "\n") %> + + let resultSelector: ResultSelector + + init(<%= (Array(1...i).map { "source\($0): Observable" }).joined(separator: ", ") %>, resultSelector: @escaping ResultSelector) { +<%= (Array(1...i).map { +" self.source\($0) = source\($0)" +}).joined(separator: "\n") %> + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink<%= i %>_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +<% } %> diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CombineLatest.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CombineLatest.swift new file mode 100644 index 000000000..caa025640 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CombineLatest.swift @@ -0,0 +1,131 @@ +// +// CombineLatest.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol CombineLatestProtocol: AnyObject { + func next(_ index: Int) + func fail(_ error: Swift.Error) + func done(_ index: Int) +} + +class CombineLatestSink + : Sink + , CombineLatestProtocol { + typealias Element = Observer.Element + + let lock = RecursiveLock() + + private let arity: Int + private var numberOfValues = 0 + private var numberOfDone = 0 + private var hasValue: [Bool] + private var isDone: [Bool] + + init(arity: Int, observer: Observer, cancel: Cancelable) { + self.arity = arity + self.hasValue = [Bool](repeating: false, count: arity) + self.isDone = [Bool](repeating: false, count: arity) + + super.init(observer: observer, cancel: cancel) + } + + func getResult() throws -> Element { + rxAbstractMethod() + } + + func next(_ index: Int) { + if !self.hasValue[index] { + self.hasValue[index] = true + self.numberOfValues += 1 + } + + if self.numberOfValues == self.arity { + do { + let result = try self.getResult() + self.forwardOn(.next(result)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + else { + var allOthersDone = true + + for i in 0 ..< self.arity { + if i != index && !self.isDone[i] { + allOthersDone = false + break + } + } + + if allOthersDone { + self.forwardOn(.completed) + self.dispose() + } + } + } + + func fail(_ error: Swift.Error) { + self.forwardOn(.error(error)) + self.dispose() + } + + func done(_ index: Int) { + if self.isDone[index] { + return + } + + self.isDone[index] = true + self.numberOfDone += 1 + + if self.numberOfDone == self.arity { + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class CombineLatestObserver + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias ValueSetter = (Element) -> Void + + private let parent: CombineLatestProtocol + + let lock: RecursiveLock + private let index: Int + private let this: Disposable + private let setLatestValue: ValueSetter + + init(lock: RecursiveLock, parent: CombineLatestProtocol, index: Int, setLatestValue: @escaping ValueSetter, this: Disposable) { + self.lock = lock + self.parent = parent + self.index = index + self.this = this + self.setLatestValue = setLatestValue + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let value): + self.setLatestValue(value) + self.parent.next(self.index) + case .error(let error): + self.this.dispose() + self.parent.fail(error) + case .completed: + self.this.dispose() + self.parent.done(self.index) + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CompactMap.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CompactMap.swift new file mode 100644 index 000000000..7dbcdfbe9 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/CompactMap.swift @@ -0,0 +1,76 @@ +// +// CompactMap.swift +// RxSwift +// +// Created by Michael Long on 04/09/2019. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into an optional form and filters all optional results. + + - parameter transform: A transform function to apply to each source element and which returns an element or nil. + - returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source. + + */ + public func compactMap(_ transform: @escaping (Element) throws -> Result?) + -> Observable { + CompactMap(source: self.asObservable(), transform: transform) + } +} + +final private class CompactMapSink: Sink, ObserverType { + typealias Transform = (SourceType) throws -> ResultType? + + typealias ResultType = Observer.Element + typealias Element = SourceType + + private let transform: Transform + + init(transform: @escaping Transform, observer: Observer, cancel: Cancelable) { + self.transform = transform + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let element): + do { + if let mappedElement = try self.transform(element) { + self.forwardOn(.next(mappedElement)) + } + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class CompactMap: Producer { + typealias Transform = (SourceType) throws -> ResultType? + + private let source: Observable + + private let transform: Transform + + init(source: Observable, transform: @escaping Transform) { + self.source = source + self.transform = transform + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { + let sink = CompactMapSink(transform: self.transform, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Concat.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Concat.swift new file mode 100644 index 000000000..b2fb1a2e5 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Concat.swift @@ -0,0 +1,131 @@ +// +// Concat.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Concatenates the second observable sequence to `self` upon successful termination of `self`. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - parameter second: Second observable sequence. + - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. + */ + public func concat(_ second: Source) -> Observable where Source.Element == Element { + Observable.concat([self.asObservable(), second.asObservable()]) + } +} + +extension ObservableType { + /** + Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ sequence: Sequence) -> Observable + where Sequence.Element == Observable { + return Concat(sources: sequence, count: nil) + } + + /** + Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ collection: Collection) -> Observable + where Collection.Element == Observable { + return Concat(sources: collection, count: Int64(collection.count)) + } + + /** + Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ sources: Observable ...) -> Observable { + Concat(sources: sources, count: Int64(sources.count)) + } +} + +final private class ConcatSink + : TailRecursiveSink + , ObserverType where Sequence.Element: ObservableConvertibleType, Sequence.Element.Element == Observer.Element { + typealias Element = Observer.Element + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event){ + switch event { + case .next: + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.schedule(.moveNext) + } + } + + override func subscribeToNext(_ source: Observable) -> Disposable { + source.subscribe(self) + } + + override func extract(_ observable: Observable) -> SequenceGenerator? { + if let source = observable as? Concat { + return (source.sources.makeIterator(), source.count) + } + else { + return nil + } + } +} + +final private class Concat: Producer where Sequence.Element: ObservableConvertibleType { + typealias Element = Sequence.Element.Element + + fileprivate let sources: Sequence + fileprivate let count: IntMax? + + init(sources: Sequence, count: IntMax?) { + self.sources = sources + self.count = count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ConcatSink(observer: observer, cancel: cancel) + let subscription = sink.run((self.sources.makeIterator(), self.count)) + return (sink: sink, subscription: subscription) + } +} + diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Create.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Create.swift new file mode 100644 index 000000000..ca81442ce --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Create.swift @@ -0,0 +1,78 @@ +// +// Create.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + // MARK: create + + /** + Creates an observable sequence from a specified subscribe method implementation. + + - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) + + - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method. + - returns: The observable sequence with the specified implementation for the `subscribe` method. + */ + public static func create(_ subscribe: @escaping (AnyObserver) -> Disposable) -> Observable { + AnonymousObservable(subscribe) + } +} + +final private class AnonymousObservableSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = AnonymousObservable + + // state + private let isStopped = AtomicInt(0) + + #if DEBUG + private let synchronizationTracker = SynchronizationTracker() + #endif + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + #if DEBUG + self.synchronizationTracker.register(synchronizationErrorMessage: .default) + defer { self.synchronizationTracker.unregister() } + #endif + switch event { + case .next: + if load(self.isStopped) == 1 { + return + } + self.forwardOn(event) + case .error, .completed: + if fetchOr(self.isStopped, 1) == 0 { + self.forwardOn(event) + self.dispose() + } + } + } + + func run(_ parent: Parent) -> Disposable { + parent.subscribeHandler(AnyObserver(self)) + } +} + +final private class AnonymousObservable: Producer { + typealias SubscribeHandler = (AnyObserver) -> Disposable + + let subscribeHandler: SubscribeHandler + + init(_ subscribeHandler: @escaping SubscribeHandler) { + self.subscribeHandler = subscribeHandler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = AnonymousObservableSink(observer: observer, cancel: cancel) + let subscription = sink.run(self) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Debounce.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Debounce.swift new file mode 100644 index 000000000..dfab00454 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Debounce.swift @@ -0,0 +1,119 @@ +// +// Debounce.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/11/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter scheduler: Scheduler to run the throttle timers on. + - returns: The throttled sequence. + */ + public func debounce(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Debounce(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final private class DebounceSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias ParentType = Debounce + + private let parent: ParentType + + let lock = RecursiveLock() + + // state + private var id = 0 as UInt64 + private var value: Element? + + let cancellable = SerialDisposable() + + init(parent: ParentType, observer: Observer, cancel: Cancelable) { + self.parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = self.parent.source.subscribe(self) + + return Disposables.create(subscription, cancellable) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let element): + self.id = self.id &+ 1 + let currentId = self.id + self.value = element + + + let scheduler = self.parent.scheduler + let dueTime = self.parent.dueTime + + let d = SingleAssignmentDisposable() + self.cancellable.disposable = d + d.setDisposable(scheduler.scheduleRelative(currentId, dueTime: dueTime, action: self.propagate)) + case .error: + self.value = nil + self.forwardOn(event) + self.dispose() + case .completed: + if let value = self.value { + self.value = nil + self.forwardOn(.next(value)) + } + self.forwardOn(.completed) + self.dispose() + } + } + + func propagate(_ currentId: UInt64) -> Disposable { + self.lock.performLocked { + let originalValue = self.value + + if let value = originalValue, self.id == currentId { + self.value = nil + self.forwardOn(.next(value)) + } + + return Disposables.create() + } + } +} + +final private class Debounce: Producer { + fileprivate let source: Observable + fileprivate let dueTime: RxTimeInterval + fileprivate let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = DebounceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Debug.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Debug.swift new file mode 100644 index 000000000..762e394fc --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Debug.swift @@ -0,0 +1,102 @@ +// +// Debug.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension ObservableType { + + /** + Prints received events for all observers on standard output. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - parameter identifier: Identifier that is printed together with event description to standard output. + - parameter trimOutput: Should output be trimmed to max 40 characters. + - returns: An observable sequence whose events are printed to standard output. + */ + public func debug(_ identifier: String? = nil, trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function) + -> Observable { + return Debug(source: self, identifier: identifier, trimOutput: trimOutput, file: file, line: line, function: function) + } +} + +private let dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" + +private func logEvent(_ identifier: String, dateFormat: DateFormatter, content: String) { + print("\(dateFormat.string(from: Date())): \(identifier) -> \(content)") +} + +final private class DebugSink: Sink, ObserverType where Observer.Element == Source.Element { + typealias Element = Observer.Element + typealias Parent = Debug + + private let parent: Parent + private let timestampFormatter = DateFormatter() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.timestampFormatter.dateFormat = dateFormat + + logEvent(self.parent.identifier, dateFormat: self.timestampFormatter, content: "subscribed") + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + let maxEventTextLength = 40 + let eventText = "\(event)" + + let eventNormalized = (eventText.count > maxEventTextLength) && self.parent.trimOutput + ? String(eventText.prefix(maxEventTextLength / 2)) + "..." + String(eventText.suffix(maxEventTextLength / 2)) + : eventText + + logEvent(self.parent.identifier, dateFormat: self.timestampFormatter, content: "Event \(eventNormalized)") + + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + + override func dispose() { + if !self.isDisposed { + logEvent(self.parent.identifier, dateFormat: self.timestampFormatter, content: "isDisposed") + } + super.dispose() + } +} + +final private class Debug: Producer { + fileprivate let identifier: String + fileprivate let trimOutput: Bool + private let source: Source + + init(source: Source, identifier: String?, trimOutput: Bool, file: String, line: UInt, function: String) { + self.trimOutput = trimOutput + if let identifier = identifier { + self.identifier = identifier + } + else { + let trimmedFile: String + if let lastIndex = file.lastIndex(of: "/") { + trimmedFile = String(file[file.index(after: lastIndex) ..< file.endIndex]) + } + else { + trimmedFile = file + } + self.identifier = "\(trimmedFile):\(line) (\(function))" + } + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Source.Element { + let sink = DebugSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Decode.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Decode.swift new file mode 100644 index 000000000..8bc73425d --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Decode.swift @@ -0,0 +1,34 @@ +// +// Decode.swift +// RxSwift +// +// Created by Shai Mishali on 24/07/2020. +// Copyright © 2020 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +public extension ObservableType where Element == Data { + /// Attempt to decode the emitted `Data` using a provided decoder. + /// + /// - parameter type: A `Decodable`-conforming type to attempt to decode to + /// - parameter decoder: A capable decoder, e.g. `JSONDecoder` or `PropertyListDecoder` + /// + /// - note: If using a custom decoder, it must conform to the `DataDecoder` protocol. + /// + /// - returns: An `Observable` of the decoded type + func decode(type: Item.Type, + decoder: Decoder) -> Observable { + map { try decoder.decode(type, from: $0) } + } +} + +/// Represents an entity capable of decoding raw `Data` +/// into a concrete `Decodable` type +public protocol DataDecoder { + func decode(_ type: Item.Type, from data: Data) throws -> Item +} + +extension JSONDecoder: DataDecoder {} +extension PropertyListDecoder: DataDecoder {} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/DefaultIfEmpty.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/DefaultIfEmpty.swift new file mode 100644 index 000000000..8d133d8f8 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/DefaultIfEmpty.swift @@ -0,0 +1,66 @@ +// +// DefaultIfEmpty.swift +// RxSwift +// +// Created by sergdort on 23/12/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Emits elements from the source observable sequence, or a default element if the source observable sequence is empty. + + - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) + + - parameter default: Default element to be sent if the source does not emit any elements + - returns: An observable sequence which emits default element end completes in case the original sequence is empty + */ + public func ifEmpty(default: Element) -> Observable { + DefaultIfEmpty(source: self.asObservable(), default: `default`) + } +} + +final private class DefaultIfEmptySink: Sink, ObserverType { + typealias Element = Observer.Element + private let `default`: Element + private var isEmpty = true + + init(default: Element, observer: Observer, cancel: Cancelable) { + self.default = `default` + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + self.isEmpty = false + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if self.isEmpty { + self.forwardOn(.next(self.default)) + } + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class DefaultIfEmpty: Producer { + private let source: Observable + private let `default`: SourceType + + init(source: Observable, `default`: SourceType) { + self.source = source + self.default = `default` + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceType { + let sink = DefaultIfEmptySink(default: self.default, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Deferred.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Deferred.swift new file mode 100644 index 000000000..b81cb1669 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Deferred.swift @@ -0,0 +1,75 @@ +// +// Deferred.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + + - seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html) + + - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. + - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + public static func deferred(_ observableFactory: @escaping () throws -> Observable) + -> Observable { + Deferred(observableFactory: observableFactory) + } +} + +final private class DeferredSink: Sink, ObserverType where Source.Element == Observer.Element { + typealias Element = Observer.Element + + private let observableFactory: () throws -> Source + + init(observableFactory: @escaping () throws -> Source, observer: Observer, cancel: Cancelable) { + self.observableFactory = observableFactory + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + do { + let result = try self.observableFactory() + return result.subscribe(self) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + return Disposables.create() + } + } + + func on(_ event: Event) { + self.forwardOn(event) + + switch event { + case .next: + break + case .error: + self.dispose() + case .completed: + self.dispose() + } + } +} + +final private class Deferred: Producer { + typealias Factory = () throws -> Source + + private let observableFactory : Factory + + init(observableFactory: @escaping Factory) { + self.observableFactory = observableFactory + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) + where Observer.Element == Source.Element { + let sink = DeferredSink(observableFactory: self.observableFactory, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Delay.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Delay.swift new file mode 100644 index 000000000..9f71c32d0 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Delay.swift @@ -0,0 +1,174 @@ +// +// Delay.swift +// RxSwift +// +// Created by tarunon on 2016/02/09. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension ObservableType { + + /** + Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed. + + - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) + + - parameter dueTime: Relative time shift of the source by. + - parameter scheduler: Scheduler to run the subscription delay timer on. + - returns: the source Observable shifted in time by the specified delay. + */ + public func delay(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Delay(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final private class DelaySink + : Sink + , ObserverType { + typealias Element = Observer.Element + typealias Source = Observable + typealias DisposeKey = Bag.KeyType + + private let lock = RecursiveLock() + + private let dueTime: RxTimeInterval + private let scheduler: SchedulerType + + private let sourceSubscription = SingleAssignmentDisposable() + private let cancelable = SerialDisposable() + + // is scheduled some action + private var active = false + // is "run loop" on different scheduler running + private var running = false + private var errorEvent: Event? + + // state + private var queue = Queue<(eventTime: RxTime, event: Event)>(capacity: 0) + + init(observer: Observer, dueTime: RxTimeInterval, scheduler: SchedulerType, cancel: Cancelable) { + self.dueTime = dueTime + self.scheduler = scheduler + super.init(observer: observer, cancel: cancel) + } + + // All of these complications in this method are caused by the fact that + // error should be propagated immediately. Error can be potentially received on different + // scheduler so this process needs to be synchronized somehow. + // + // Another complication is that scheduler is potentially concurrent so internal queue is used. + func drainQueue(state: (), scheduler: AnyRecursiveScheduler<()>) { + self.lock.lock() + let hasFailed = self.errorEvent != nil + if !hasFailed { + self.running = true + } + self.lock.unlock() + + if hasFailed { + return + } + + var ranAtLeastOnce = false + + while true { + self.lock.lock() + let errorEvent = self.errorEvent + + let eventToForwardImmediately = ranAtLeastOnce ? nil : self.queue.dequeue()?.event + let nextEventToScheduleOriginalTime: Date? = ranAtLeastOnce && !self.queue.isEmpty ? self.queue.peek().eventTime : nil + + if errorEvent == nil { + if eventToForwardImmediately != nil { + } + else if nextEventToScheduleOriginalTime != nil { + self.running = false + } + else { + self.running = false + self.active = false + } + } + self.lock.unlock() + + if let errorEvent = errorEvent { + self.forwardOn(errorEvent) + self.dispose() + return + } + else { + if let eventToForwardImmediately = eventToForwardImmediately { + ranAtLeastOnce = true + self.forwardOn(eventToForwardImmediately) + if case .completed = eventToForwardImmediately { + self.dispose() + return + } + } + else if let nextEventToScheduleOriginalTime = nextEventToScheduleOriginalTime { + scheduler.schedule((), dueTime: self.dueTime.reduceWithSpanBetween(earlierDate: nextEventToScheduleOriginalTime, laterDate: self.scheduler.now)) + return + } + else { + return + } + } + } + } + + func on(_ event: Event) { + if event.isStopEvent { + self.sourceSubscription.dispose() + } + + switch event { + case .error: + self.lock.lock() + let shouldSendImmediately = !self.running + self.queue = Queue(capacity: 0) + self.errorEvent = event + self.lock.unlock() + + if shouldSendImmediately { + self.forwardOn(event) + self.dispose() + } + default: + self.lock.lock() + let shouldSchedule = !self.active + self.active = true + self.queue.enqueue((self.scheduler.now, event)) + self.lock.unlock() + + if shouldSchedule { + self.cancelable.disposable = self.scheduler.scheduleRecursive((), dueTime: self.dueTime, action: self.drainQueue) + } + } + } + + func run(source: Observable) -> Disposable { + self.sourceSubscription.setDisposable(source.subscribe(self)) + return Disposables.create(sourceSubscription, cancelable) + } +} + +final private class Delay: Producer { + private let source: Observable + private let dueTime: RxTimeInterval + private let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = DelaySink(observer: observer, dueTime: self.dueTime, scheduler: self.scheduler, cancel: cancel) + let subscription = sink.run(source: self.source) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/DelaySubscription.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/DelaySubscription.swift new file mode 100644 index 000000000..fd8c4951f --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/DelaySubscription.swift @@ -0,0 +1,58 @@ +// +// DelaySubscription.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. + + - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) + + - parameter dueTime: Relative time shift of the subscription. + - parameter scheduler: Scheduler to run the subscription delay timer on. + - returns: Time-shifted sequence. + */ + public func delaySubscription(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + DelaySubscription(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final private class DelaySubscriptionSink + : Sink, ObserverType { + typealias Element = Observer.Element + + func on(_ event: Event) { + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + +} + +final private class DelaySubscription: Producer { + private let source: Observable + private let dueTime: RxTimeInterval + private let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = DelaySubscriptionSink(observer: observer, cancel: cancel) + let subscription = self.scheduler.scheduleRelative((), dueTime: self.dueTime) { _ in + return self.source.subscribe(sink) + } + + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Dematerialize.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Dematerialize.swift new file mode 100644 index 000000000..2ccd54620 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Dematerialize.swift @@ -0,0 +1,51 @@ +// +// Dematerialize.swift +// RxSwift +// +// Created by Jamie Pinkham on 3/13/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where Element: EventConvertible { + /** + Convert any previously materialized Observable into it's original form. + - seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html) + - returns: The dematerialized observable sequence. + */ + public func dematerialize() -> Observable { + Dematerialize(source: self.asObservable()) + } + +} + +private final class DematerializeSink: Sink, ObserverType where Observer.Element == T.Element { + fileprivate func on(_ event: Event) { + switch event { + case .next(let element): + self.forwardOn(element.event) + if element.event.isStopEvent { + self.dispose() + } + case .completed: + self.forwardOn(.completed) + self.dispose() + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class Dematerialize: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == T.Element { + let sink = DematerializeSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/DistinctUntilChanged.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/DistinctUntilChanged.swift new file mode 100644 index 000000000..c127b5aa5 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/DistinctUntilChanged.swift @@ -0,0 +1,137 @@ +// +// DistinctUntilChanged.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where Element: Equatable { + + /** + Returns an observable sequence that contains only distinct contiguous elements according to equality operator. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence. + */ + public func distinctUntilChanged() + -> Observable { + self.distinctUntilChanged({ $0 }, comparer: { ($0 == $1) }) + } +} + +extension ObservableType { + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter keySelector: A function to compute the comparison key for each element. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (Element) throws -> Key) + -> Observable { + self.distinctUntilChanged(keySelector, comparer: { $0 == $1 }) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence. + */ + public func distinctUntilChanged(_ comparer: @escaping (Element, Element) throws -> Bool) + -> Observable { + self.distinctUntilChanged({ $0 }, comparer: comparer) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter keySelector: A function to compute the comparison key for each element. + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (Element) throws -> K, comparer: @escaping (K, K) throws -> Bool) + -> Observable { + return DistinctUntilChanged(source: self.asObservable(), selector: keySelector, comparer: comparer) + } + + /** + Returns an observable sequence that contains only contiguous elements with distinct values in the provided key path on each object. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator on the provided key path + */ + public func distinctUntilChanged(at keyPath: KeyPath) -> + Observable { + self.distinctUntilChanged { $0[keyPath: keyPath] == $1[keyPath: keyPath] } + } +} + +final private class DistinctUntilChangedSink: Sink, ObserverType { + typealias Element = Observer.Element + + private let parent: DistinctUntilChanged + private var currentKey: Key? + + init(parent: DistinctUntilChanged, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let key = try self.parent.selector(value) + var areEqual = false + if let currentKey = self.currentKey { + areEqual = try self.parent.comparer(currentKey, key) + } + + if areEqual { + return + } + + self.currentKey = key + + self.forwardOn(event) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + case .error, .completed: + self.forwardOn(event) + self.dispose() + } + } +} + +final private class DistinctUntilChanged: Producer { + typealias KeySelector = (Element) throws -> Key + typealias EqualityComparer = (Key, Key) throws -> Bool + + private let source: Observable + fileprivate let selector: KeySelector + fileprivate let comparer: EqualityComparer + + init(source: Observable, selector: @escaping KeySelector, comparer: @escaping EqualityComparer) { + self.source = source + self.selector = selector + self.comparer = comparer + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = DistinctUntilChangedSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Do.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Do.swift new file mode 100644 index 000000000..3c8c68b3d --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Do.swift @@ -0,0 +1,112 @@ +// +// Do.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + 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 afterNext: Action to invoke for each element after the observable has passed an onNext event along to its downstream. + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - parameter afterError: Action to invoke after errored termination of the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter afterCompleted: Action to invoke after graceful termination of the observable sequence. + - parameter onSubscribe: Action to invoke before subscribing to source observable sequence. + - parameter onSubscribed: Action to invoke after subscribing to source observable sequence. + - parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed. + - returns: The source sequence with the side-effecting behavior applied. + */ + public func `do`(onNext: ((Element) throws -> Void)? = nil, afterNext: ((Element) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, afterError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, afterCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) + -> Observable { + return Do(source: self.asObservable(), eventHandler: { e in + switch e { + case .next(let element): + try onNext?(element) + case .error(let e): + try onError?(e) + case .completed: + try onCompleted?() + } + }, afterEventHandler: { e in + switch e { + case .next(let element): + try afterNext?(element) + case .error(let e): + try afterError?(e) + case .completed: + try afterCompleted?() + } + }, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose) + } +} + +final private class DoSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias EventHandler = (Event) throws -> Void + typealias AfterEventHandler = (Event) throws -> Void + + private let eventHandler: EventHandler + private let afterEventHandler: AfterEventHandler + + init(eventHandler: @escaping EventHandler, afterEventHandler: @escaping AfterEventHandler, observer: Observer, cancel: Cancelable) { + self.eventHandler = eventHandler + self.afterEventHandler = afterEventHandler + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + do { + try self.eventHandler(event) + self.forwardOn(event) + try self.afterEventHandler(event) + if event.isStopEvent { + self.dispose() + } + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class Do: Producer { + typealias EventHandler = (Event) throws -> Void + typealias AfterEventHandler = (Event) throws -> Void + + private let source: Observable + private let eventHandler: EventHandler + private let afterEventHandler: AfterEventHandler + private let onSubscribe: (() -> Void)? + private let onSubscribed: (() -> Void)? + private let onDispose: (() -> Void)? + + init(source: Observable, eventHandler: @escaping EventHandler, afterEventHandler: @escaping AfterEventHandler, onSubscribe: (() -> Void)?, onSubscribed: (() -> Void)?, onDispose: (() -> Void)?) { + self.source = source + self.eventHandler = eventHandler + self.afterEventHandler = afterEventHandler + self.onSubscribe = onSubscribe + self.onSubscribed = onSubscribed + self.onDispose = onDispose + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + self.onSubscribe?() + let sink = DoSink(eventHandler: self.eventHandler, afterEventHandler: self.afterEventHandler, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + self.onSubscribed?() + let onDispose = self.onDispose + let allSubscriptions = Disposables.create { + subscription.dispose() + onDispose?() + } + return (sink: sink, subscription: allSubscriptions) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/ElementAt.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/ElementAt.swift new file mode 100644 index 000000000..3f09c7087 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/ElementAt.swift @@ -0,0 +1,105 @@ +// +// ElementAt.swift +// RxSwift +// +// Created by Junior B. on 21/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns a sequence emitting only element _n_ emitted by an Observable + + - seealso: [elementAt operator on reactivex.io](http://reactivex.io/documentation/operators/elementat.html) + + - parameter index: The index of the required element (starting from 0). + - returns: An observable sequence that emits the desired element as its own sole emission. + */ + @available(*, deprecated, renamed: "element(at:)") + public func elementAt(_ index: Int) + -> Observable { + element(at: index) + } + + /** + Returns a sequence emitting only element _n_ emitted by an Observable + + - seealso: [elementAt operator on reactivex.io](http://reactivex.io/documentation/operators/elementat.html) + + - parameter index: The index of the required element (starting from 0). + - returns: An observable sequence that emits the desired element as its own sole emission. + */ + public func element(at index: Int) + -> Observable { + ElementAt(source: self.asObservable(), index: index, throwOnEmpty: true) + } +} + +final private class ElementAtSink: Sink, ObserverType { + typealias SourceType = Observer.Element + typealias Parent = ElementAt + + let parent: Parent + var i: Int + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.i = parent.index + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + + if self.i == 0 { + self.forwardOn(event) + self.forwardOn(.completed) + self.dispose() + } + + do { + _ = try decrementChecked(&self.i) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + return + } + + case .error(let e): + self.forwardOn(.error(e)) + self.dispose() + case .completed: + if self.parent.throwOnEmpty { + self.forwardOn(.error(RxError.argumentOutOfRange)) + } else { + self.forwardOn(.completed) + } + + self.dispose() + } + } +} + +final private class ElementAt: Producer { + let source: Observable + let throwOnEmpty: Bool + let index: Int + + init(source: Observable, index: Int, throwOnEmpty: Bool) { + if index < 0 { + rxFatalError("index can't be negative") + } + + self.source = source + self.index = index + self.throwOnEmpty = throwOnEmpty + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceType { + let sink = ElementAtSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Empty.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Empty.swift new file mode 100644 index 000000000..9ca596594 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Empty.swift @@ -0,0 +1,27 @@ +// +// Empty.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. + + - seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: An observable sequence with no elements. + */ + public static func empty() -> Observable { + EmptyProducer() + } +} + +final private class EmptyProducer: Producer { + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + observer.on(.completed) + return Disposables.create() + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Enumerated.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Enumerated.swift new file mode 100644 index 000000000..ef8a0ff02 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Enumerated.swift @@ -0,0 +1,61 @@ +// +// Enumerated.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/6/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Enumerates the elements of an observable sequence. + + - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) + + - returns: An observable sequence that contains tuples of source sequence elements and their indexes. + */ + public func enumerated() + -> Observable<(index: Int, element: Element)> { + Enumerated(source: self.asObservable()) + } +} + +final private class EnumeratedSink: Sink, ObserverType where Observer.Element == (index: Int, element: Element) { + var index = 0 + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let nextIndex = try incrementChecked(&self.index) + let next = (index: nextIndex, element: value) + self.forwardOn(.next(next)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .completed: + self.forwardOn(.completed) + self.dispose() + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class Enumerated: Producer<(index: Int, element: Element)> { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == (index: Int, element: Element) { + let sink = EnumeratedSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Error.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Error.swift new file mode 100644 index 000000000..2e722d670 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Error.swift @@ -0,0 +1,33 @@ +// +// Error.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an observable sequence that terminates with an `error`. + + - seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: The observable sequence that terminates with specified error. + */ + public static func error(_ error: Swift.Error) -> Observable { + ErrorProducer(error: error) + } +} + +final private class ErrorProducer: Producer { + private let error: Swift.Error + + init(error: Swift.Error) { + self.error = error + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + observer.on(.error(self.error)) + return Disposables.create() + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Filter.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Filter.swift new file mode 100644 index 000000000..61d3ce793 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Filter.swift @@ -0,0 +1,86 @@ +// +// Filter.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Filters the elements of an observable sequence based on a predicate. + + - seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html) + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. + */ + public func filter(_ predicate: @escaping (Element) throws -> Bool) + -> Observable { + Filter(source: self.asObservable(), predicate: predicate) + } +} + +extension ObservableType { + /** + Skips elements and completes (or errors) when the observable sequence completes (or errors). Equivalent to filter that always returns false. + + - seealso: [ignoreElements operator on reactivex.io](http://reactivex.io/documentation/operators/ignoreelements.html) + + - returns: An observable sequence that skips all elements of the source sequence. + */ + public func ignoreElements() + -> Observable { + self.flatMap { _ in Observable.empty() } + } +} + +final private class FilterSink: Sink, ObserverType { + typealias Predicate = (Element) throws -> Bool + typealias Element = Observer.Element + + private let predicate: Predicate + + init(predicate: @escaping Predicate, observer: Observer, cancel: Cancelable) { + self.predicate = predicate + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let satisfies = try self.predicate(value) + if satisfies { + self.forwardOn(.next(value)) + } + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .completed, .error: + self.forwardOn(event) + self.dispose() + } + } +} + +final private class Filter: Producer { + typealias Predicate = (Element) throws -> Bool + + private let source: Observable + private let predicate: Predicate + + init(source: Observable, predicate: @escaping Predicate) { + self.source = source + self.predicate = predicate + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = FilterSink(predicate: self.predicate, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/First.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/First.swift new file mode 100644 index 000000000..001411485 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/First.swift @@ -0,0 +1,41 @@ +// +// First.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/31/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +private final class FirstSink : Sink, ObserverType where Observer.Element == Element? { + typealias Parent = First + + func on(_ event: Event) { + switch event { + case .next(let value): + self.forwardOn(.next(value)) + self.forwardOn(.completed) + self.dispose() + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.next(nil)) + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class First: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element? { + let sink = FirstSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Generate.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Generate.swift new file mode 100644 index 000000000..7b924b381 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Generate.swift @@ -0,0 +1,87 @@ +// +// Generate.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler + to run the loop send out observer messages. + + - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) + + - parameter initialState: Initial state. + - parameter condition: Condition to terminate generation (upon returning `false`). + - parameter iterate: Iteration step function. + - parameter scheduler: Scheduler on which to run the generator loop. + - returns: The generated sequence. + */ + public static func generate(initialState: Element, condition: @escaping (Element) throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: @escaping (Element) throws -> Element) -> Observable { + Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler) + } +} + +final private class GenerateSink: Sink { + typealias Parent = Generate + + private let parent: Parent + + private var state: Sequence + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.state = parent.initialState + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRecursive(true) { isFirst, recurse -> Void in + do { + if !isFirst { + self.state = try self.parent.iterate(self.state) + } + + if try self.parent.condition(self.state) { + let result = try self.parent.resultSelector(self.state) + self.forwardOn(.next(result)) + + recurse(false) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + } + } +} + +final private class Generate: Producer { + fileprivate let initialState: Sequence + fileprivate let condition: (Sequence) throws -> Bool + fileprivate let iterate: (Sequence) throws -> Sequence + fileprivate let resultSelector: (Sequence) throws -> Element + fileprivate let scheduler: ImmediateSchedulerType + + init(initialState: Sequence, condition: @escaping (Sequence) throws -> Bool, iterate: @escaping (Sequence) throws -> Sequence, resultSelector: @escaping (Sequence) throws -> Element, scheduler: ImmediateSchedulerType) { + self.initialState = initialState + self.condition = condition + self.iterate = iterate + self.resultSelector = resultSelector + self.scheduler = scheduler + super.init() + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = GenerateSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/GroupBy.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/GroupBy.swift new file mode 100644 index 000000000..88cbda767 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/GroupBy.swift @@ -0,0 +1,133 @@ +// +// GroupBy.swift +// RxSwift +// +// Created by Tomi Koskinen on 01/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /* + Groups the elements of an observable sequence according to a specified key selector function. + + - seealso: [groupBy operator on reactivex.io](http://reactivex.io/documentation/operators/groupby.html) + + - parameter keySelector: A function to extract the key for each element. + - returns: A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + */ + public func groupBy(keySelector: @escaping (Element) throws -> Key) + -> Observable> { + GroupBy(source: self.asObservable(), selector: keySelector) + } +} + +final private class GroupedObservableImpl: Observable { + private var subject: PublishSubject + private var refCount: RefCountDisposable + + init(subject: PublishSubject, refCount: RefCountDisposable) { + self.subject = subject + self.refCount = refCount + } + + override public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + let release = self.refCount.retain() + let subscription = self.subject.subscribe(observer) + return Disposables.create(release, subscription) + } +} + + +final private class GroupBySink + : Sink + , ObserverType where Observer.Element == GroupedObservable { + typealias ResultType = Observer.Element + typealias Parent = GroupBy + + private let parent: Parent + private let subscription = SingleAssignmentDisposable() + private var refCountDisposable: RefCountDisposable! + private var groupedSubjectTable: [Key: PublishSubject] + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.groupedSubjectTable = [Key: PublishSubject]() + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + self.refCountDisposable = RefCountDisposable(disposable: self.subscription) + + self.subscription.setDisposable(self.parent.source.subscribe(self)) + + return self.refCountDisposable + } + + private func onGroupEvent(key: Key, value: Element) { + if let writer = self.groupedSubjectTable[key] { + writer.on(.next(value)) + } else { + let writer = PublishSubject() + self.groupedSubjectTable[key] = writer + + let group = GroupedObservable( + key: key, + source: GroupedObservableImpl(subject: writer, refCount: refCountDisposable) + ) + + self.forwardOn(.next(group)) + writer.on(.next(value)) + } + } + + final func on(_ event: Event) { + switch event { + case let .next(value): + do { + let groupKey = try self.parent.selector(value) + self.onGroupEvent(key: groupKey, value: value) + } + catch let e { + self.error(e) + return + } + case let .error(e): + self.error(e) + case .completed: + self.forwardOnGroups(event: .completed) + self.forwardOn(.completed) + self.subscription.dispose() + self.dispose() + } + } + + final func error(_ error: Swift.Error) { + self.forwardOnGroups(event: .error(error)) + self.forwardOn(.error(error)) + self.subscription.dispose() + self.dispose() + } + + final func forwardOnGroups(event: Event) { + for writer in self.groupedSubjectTable.values { + writer.on(event) + } + } +} + +final private class GroupBy: Producer> { + typealias KeySelector = (Element) throws -> Key + + fileprivate let source: Observable + fileprivate let selector: KeySelector + + init(source: Observable, selector: @escaping KeySelector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == GroupedObservable { + let sink = GroupBySink(parent: self, observer: observer, cancel: cancel) + return (sink: sink, subscription: sink.run()) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Just.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Just.swift new file mode 100644 index 000000000..93490837f --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Just.swift @@ -0,0 +1,87 @@ +// +// Just.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an observable sequence that contains a single element. + + - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) + + - parameter element: Single element in the resulting observable sequence. + - returns: An observable sequence containing the single specified element. + */ + public static func just(_ element: Element) -> Observable { + Just(element: element) + } + + /** + Returns an observable sequence that contains a single element. + + - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) + + - parameter element: Single element in the resulting observable sequence. + - parameter scheduler: Scheduler to send the single element on. + - returns: An observable sequence containing the single specified element. + */ + public static func just(_ element: Element, scheduler: ImmediateSchedulerType) -> Observable { + JustScheduled(element: element, scheduler: scheduler) + } +} + +final private class JustScheduledSink: Sink { + typealias Parent = JustScheduled + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let scheduler = self.parent.scheduler + return scheduler.schedule(self.parent.element) { element in + self.forwardOn(.next(element)) + return scheduler.schedule(()) { _ in + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } + } +} + +final private class JustScheduled: Producer { + fileprivate let scheduler: ImmediateSchedulerType + fileprivate let element: Element + + init(element: Element, scheduler: ImmediateSchedulerType) { + self.scheduler = scheduler + self.element = element + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = JustScheduledSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class Just: Producer { + private let element: Element + + init(element: Element) { + self.element = element + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + observer.on(.next(self.element)) + observer.on(.completed) + return Disposables.create() + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Map.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Map.swift new file mode 100644 index 000000000..693794431 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Map.swift @@ -0,0 +1,76 @@ +// +// Map.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a new form. + + - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) + + - parameter transform: A transform function to apply to each source element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. + + */ + public func map(_ transform: @escaping (Element) throws -> Result) + -> Observable { + Map(source: self.asObservable(), transform: transform) + } +} + +final private class MapSink: Sink, ObserverType { + typealias Transform = (SourceType) throws -> ResultType + + typealias ResultType = Observer.Element + + private let transform: Transform + + init(transform: @escaping Transform, observer: Observer, cancel: Cancelable) { + self.transform = transform + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let element): + do { + let mappedElement = try self.transform(element) + self.forwardOn(.next(mappedElement)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class Map: Producer { + typealias Transform = (SourceType) throws -> ResultType + + private let source: Observable + + private let transform: Transform + + init(source: Observable, transform: @escaping Transform) { + self.source = source + self.transform = transform + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { + let sink = MapSink(transform: self.transform, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Materialize.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Materialize.swift new file mode 100644 index 000000000..e2577be5d --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Materialize.swift @@ -0,0 +1,44 @@ +// +// Materialize.swift +// RxSwift +// +// Created by sergdort on 08/03/2017. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Convert any Observable into an Observable of its events. + - seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html) + - returns: An observable sequence that wraps events in an Event. The returned Observable never errors, but it does complete after observing all of the events of the underlying Observable. + */ + public func materialize() -> Observable> { + Materialize(source: self.asObservable()) + } +} + +private final class MaterializeSink: Sink, ObserverType where Observer.Element == Event { + + func on(_ event: Event) { + self.forwardOn(.next(event)) + if event.isStopEvent { + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class Materialize: Producer> { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = MaterializeSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Merge.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Merge.swift new file mode 100644 index 000000000..51a646291 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Merge.swift @@ -0,0 +1,600 @@ +// +// Merge.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + + - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. + */ + public func flatMap(_ selector: @escaping (Element) throws -> Source) + -> Observable { + return FlatMap(source: self.asObservable(), selector: selector) + } + +} + +extension ObservableType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + If element is received while there is some projected observable sequence being merged it will simply be ignored. + + - seealso: [flatMapFirst operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated. + */ + public func flatMapFirst(_ selector: @escaping (Element) throws -> Source) + -> Observable { + return FlatMapFirst(source: self.asObservable(), selector: selector) + } +} + +extension ObservableType where Element: ObservableConvertibleType { + + /** + Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public func merge() -> Observable { + Merge(source: self.asObservable()) + } + + /** + Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently. + - returns: The observable sequence that merges the elements of the inner sequences. + */ + public func merge(maxConcurrent: Int) + -> Observable { + MergeLimited(source: self.asObservable(), maxConcurrent: maxConcurrent) + } +} + +extension ObservableType where Element: ObservableConvertibleType { + + /** + Concatenates all inner observable sequences, as long as the previous observable sequence terminated successfully. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order. + */ + public func concat() -> Observable { + self.merge(maxConcurrent: 1) + } +} + +extension ObservableType { + /** + Merges elements from all observable sequences from collection into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: Collection) -> Observable where Collection.Element == Observable { + MergeArray(sources: Array(sources)) + } + + /** + Merges elements from all observable sequences from array into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Array of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: [Observable]) -> Observable { + MergeArray(sources: sources) + } + + /** + Merges elements from all observable sequences into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: Observable...) -> Observable { + MergeArray(sources: sources) + } +} + +// MARK: concatMap + +extension ObservableType { + /** + Projects each element of an observable sequence to an observable sequence and concatenates the resulting observable sequences into one observable sequence. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order. + */ + + public func concatMap(_ selector: @escaping (Element) throws -> Source) + -> Observable { + return ConcatMap(source: self.asObservable(), selector: selector) + } +} + +private final class MergeLimitedSinkIter + : ObserverType + , LockOwnerType + , SynchronizedOnType where SourceSequence.Element == Observer.Element { + typealias Element = Observer.Element + typealias DisposeKey = CompositeDisposable.DisposeKey + typealias Parent = MergeLimitedSink + + private let parent: Parent + private let disposeKey: DisposeKey + + var lock: RecursiveLock { + self.parent.lock + } + + init(parent: Parent, disposeKey: DisposeKey) { + self.parent = parent + self.disposeKey = disposeKey + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + self.parent.forwardOn(event) + case .error: + self.parent.forwardOn(event) + self.parent.dispose() + case .completed: + self.parent.group.remove(for: self.disposeKey) + if let next = self.parent.queue.dequeue() { + self.parent.subscribe(next, group: self.parent.group) + } + else { + self.parent.activeCount -= 1 + + if self.parent.stopped && self.parent.activeCount == 0 { + self.parent.forwardOn(.completed) + self.parent.dispose() + } + } + } + } +} + +private final class ConcatMapSink: MergeLimitedSink where Observer.Element == SourceSequence.Element { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let selector: Selector + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self.selector = selector + super.init(maxConcurrent: 1, observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceElement) throws -> SourceSequence { + try self.selector(element) + } +} + +private final class MergeLimitedBasicSink: MergeLimitedSink where Observer.Element == SourceSequence.Element { + + override func performMap(_ element: SourceSequence) throws -> SourceSequence { + element + } +} + +private class MergeLimitedSink + : Sink + , ObserverType where Observer.Element == SourceSequence.Element { + typealias QueueType = Queue + + let maxConcurrent: Int + + let lock = RecursiveLock() + + // state + var stopped = false + var activeCount = 0 + var queue = QueueType(capacity: 2) + + let sourceSubscription = SingleAssignmentDisposable() + let group = CompositeDisposable() + + init(maxConcurrent: Int, observer: Observer, cancel: Cancelable) { + self.maxConcurrent = maxConcurrent + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + _ = self.group.insert(self.sourceSubscription) + + let disposable = source.subscribe(self) + self.sourceSubscription.setDisposable(disposable) + return self.group + } + + func subscribe(_ innerSource: SourceSequence, group: CompositeDisposable) { + let subscription = SingleAssignmentDisposable() + + let key = group.insert(subscription) + + if let key = key { + let observer = MergeLimitedSinkIter(parent: self, disposeKey: key) + + let disposable = innerSource.asObservable().subscribe(observer) + subscription.setDisposable(disposable) + } + } + + func performMap(_ element: SourceElement) throws -> SourceSequence { + rxAbstractMethod() + } + + @inline(__always) + final private func nextElementArrived(element: SourceElement) -> SourceSequence? { + self.lock.performLocked { + let subscribe: Bool + if self.activeCount < self.maxConcurrent { + self.activeCount += 1 + subscribe = true + } + else { + do { + let value = try self.performMap(element) + self.queue.enqueue(value) + } catch { + self.forwardOn(.error(error)) + self.dispose() + } + subscribe = false + } + + if subscribe { + do { + return try self.performMap(element) + } catch { + self.forwardOn(.error(error)) + self.dispose() + } + } + + return nil + } + } + + func on(_ event: Event) { + switch event { + case .next(let element): + if let sequence = self.nextElementArrived(element: element) { + self.subscribe(sequence, group: self.group) + } + case .error(let error): + self.lock.performLocked { + self.forwardOn(.error(error)) + self.dispose() + } + case .completed: + self.lock.performLocked { + if self.activeCount == 0 { + self.forwardOn(.completed) + self.dispose() + } + else { + self.sourceSubscription.dispose() + } + + self.stopped = true + } + } + } +} + +final private class MergeLimited: Producer { + private let source: Observable + private let maxConcurrent: Int + + init(source: Observable, maxConcurrent: Int) { + self.source = source + self.maxConcurrent = maxConcurrent + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = MergeLimitedBasicSink(maxConcurrent: self.maxConcurrent, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +// MARK: Merge + +private final class MergeBasicSink : MergeSink where Observer.Element == Source.Element { + override func performMap(_ element: Source) throws -> Source { + element + } +} + +// MARK: flatMap + +private final class FlatMapSink : MergeSink where Observer.Element == SourceSequence.Element { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let selector: Selector + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self.selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceElement) throws -> SourceSequence { + try self.selector(element) + } +} + +// MARK: FlatMapFirst + +private final class FlatMapFirstSink : MergeSink where Observer.Element == SourceSequence.Element { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let selector: Selector + + override var subscribeNext: Bool { + self.activeCount == 0 + } + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self.selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceElement) throws -> SourceSequence { + try self.selector(element) + } +} + +private final class MergeSinkIter : ObserverType where Observer.Element == SourceSequence.Element { + typealias Parent = MergeSink + typealias DisposeKey = CompositeDisposable.DisposeKey + typealias Element = Observer.Element + + private let parent: Parent + private let disposeKey: DisposeKey + + init(parent: Parent, disposeKey: DisposeKey) { + self.parent = parent + self.disposeKey = disposeKey + } + + func on(_ event: Event) { + self.parent.lock.performLocked { + switch event { + case .next(let value): + self.parent.forwardOn(.next(value)) + case .error(let error): + self.parent.forwardOn(.error(error)) + self.parent.dispose() + case .completed: + self.parent.group.remove(for: self.disposeKey) + self.parent.activeCount -= 1 + self.parent.checkCompleted() + } + } + } +} + + +private class MergeSink + : Sink + , ObserverType where Observer.Element == SourceSequence.Element { + typealias ResultType = Observer.Element + typealias Element = SourceElement + + let lock = RecursiveLock() + + var subscribeNext: Bool { + true + } + + // state + let group = CompositeDisposable() + let sourceSubscription = SingleAssignmentDisposable() + + var activeCount = 0 + var stopped = false + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func performMap(_ element: SourceElement) throws -> SourceSequence { + rxAbstractMethod() + } + + @inline(__always) + final private func nextElementArrived(element: SourceElement) -> SourceSequence? { + self.lock.performLocked { + if !self.subscribeNext { + return nil + } + + do { + let value = try self.performMap(element) + self.activeCount += 1 + return value + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + return nil + } + } + } + + func on(_ event: Event) { + switch event { + case .next(let element): + if let value = self.nextElementArrived(element: element) { + self.subscribeInner(value.asObservable()) + } + case .error(let error): + self.lock.performLocked { + self.forwardOn(.error(error)) + self.dispose() + } + case .completed: + self.lock.performLocked { + self.stopped = true + self.sourceSubscription.dispose() + self.checkCompleted() + } + } + } + + func subscribeInner(_ source: Observable) { + let iterDisposable = SingleAssignmentDisposable() + if let disposeKey = self.group.insert(iterDisposable) { + let iter = MergeSinkIter(parent: self, disposeKey: disposeKey) + let subscription = source.subscribe(iter) + iterDisposable.setDisposable(subscription) + } + } + + func run(_ sources: [Observable]) -> Disposable { + self.activeCount += sources.count + + for source in sources { + self.subscribeInner(source) + } + + self.stopped = true + + self.checkCompleted() + + return self.group + } + + @inline(__always) + func checkCompleted() { + if self.stopped && self.activeCount == 0 { + self.forwardOn(.completed) + self.dispose() + } + } + + func run(_ source: Observable) -> Disposable { + _ = self.group.insert(self.sourceSubscription) + + let subscription = source.subscribe(self) + self.sourceSubscription.setDisposable(subscription) + + return self.group + } +} + +// MARK: Producers + +final private class FlatMap: Producer { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let source: Observable + + private let selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = FlatMapSink(selector: self.selector, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final private class FlatMapFirst: Producer { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let source: Observable + + private let selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = FlatMapFirstSink(selector: self.selector, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final class ConcatMap: Producer { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let source: Observable + private let selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = ConcatMapSink(selector: self.selector, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final class Merge : Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = MergeBasicSink(observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final private class MergeArray: Producer { + private let sources: [Observable] + + init(sources: [Observable]) { + self.sources = sources + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = MergeBasicSink, Observer>(observer: observer, cancel: cancel) + let subscription = sink.run(self.sources) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Multicast.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Multicast.swift new file mode 100644 index 000000000..1ebcf0212 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Multicast.swift @@ -0,0 +1,405 @@ +// +// Multicast.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** + Represents an observable wrapper that can be connected and disconnected from its underlying observable sequence. + */ +public class ConnectableObservable + : Observable + , ConnectableObservableType { + + /** + Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established. + + - returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence. + */ + public func connect() -> Disposable { + rxAbstractMethod() + } +} + +extension ObservableType { + + /** + Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. + + Each subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's invocation. + + For specializations with fixed subject types, see `publish` and `replay`. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter subjectSelector: Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. + - parameter selector: Selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + public func multicast(_ subjectSelector: @escaping () throws -> Subject, selector: @escaping (Observable) throws -> Observable) + -> Observable where Subject.Observer.Element == Element { + return Multicast( + source: self.asObservable(), + subjectSelector: subjectSelector, + selector: selector + ) + } +} + +extension ObservableType { + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence. + + This operator is a specialization of `multicast` using a `PublishSubject`. + + - seealso: [publish operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func publish() -> ConnectableObservable { + self.multicast { PublishSubject() } + } +} + +extension ObservableType { + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying bufferSize elements. + + This operator is a specialization of `multicast` using a `ReplaySubject`. + + - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - parameter bufferSize: Maximum element count of the replay buffer. + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func replay(_ bufferSize: Int) + -> ConnectableObservable { + self.multicast { ReplaySubject.create(bufferSize: bufferSize) } + } + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying all elements. + + This operator is a specialization of `multicast` using a `ReplaySubject`. + + - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func replayAll() + -> ConnectableObservable { + self.multicast { ReplaySubject.createUnbounded() } + } +} + +extension ConnectableObservableType { + + /** + Returns an observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. + + - seealso: [refCount operator on reactivex.io](http://reactivex.io/documentation/operators/refcount.html) + + - returns: An observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. + */ + public func refCount() -> Observable { + RefCount(source: self) + } +} + +extension ObservableType { + + /** + Multicasts the source sequence notifications through the specified subject to the resulting connectable observable. + + Upon connection of the connectable observable, the subject is subscribed to the source exactly one, and messages are forwarded to the observers registered with the connectable observable. + + For specializations with fixed subject types, see `publish` and `replay`. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter subject: Subject to push source elements into. + - returns: A connectable observable sequence that upon connection causes the source sequence to push results into the specified subject. + */ + public func multicast(_ subject: Subject) + -> ConnectableObservable where Subject.Observer.Element == Element { + ConnectableObservableAdapter(source: self.asObservable(), makeSubject: { subject }) + } + + /** + Multicasts the source sequence notifications through an instantiated subject to the resulting connectable observable. + + Upon connection of the connectable observable, the subject is subscribed to the source exactly one, and messages are forwarded to the observers registered with the connectable observable. + + Subject is cleared on connection disposal or in case source sequence produces terminal event. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter makeSubject: Factory function used to instantiate a subject for each connection. + - returns: A connectable observable sequence that upon connection causes the source sequence to push results into the specified subject. + */ + public func multicast(makeSubject: @escaping () -> Subject) + -> ConnectableObservable where Subject.Observer.Element == Element { + ConnectableObservableAdapter(source: self.asObservable(), makeSubject: makeSubject) + } +} + +final private class Connection: ObserverType, Disposable { + typealias Element = Subject.Observer.Element + + private var lock: RecursiveLock + // state + private var parent: ConnectableObservableAdapter? + private var subscription : Disposable? + private var subjectObserver: Subject.Observer + + private let disposed = AtomicInt(0) + + init(parent: ConnectableObservableAdapter, subjectObserver: Subject.Observer, lock: RecursiveLock, subscription: Disposable) { + self.parent = parent + self.subscription = subscription + self.lock = lock + self.subjectObserver = subjectObserver + } + + func on(_ event: Event) { + if isFlagSet(self.disposed, 1) { + return + } + if event.isStopEvent { + self.dispose() + } + self.subjectObserver.on(event) + } + + func dispose() { + lock.lock(); defer { lock.unlock() } + fetchOr(self.disposed, 1) + guard let parent = self.parent else { + return + } + + if parent.connection === self { + parent.connection = nil + parent.subject = nil + } + self.parent = nil + + self.subscription?.dispose() + self.subscription = nil + } +} + +final private class ConnectableObservableAdapter + : ConnectableObservable { + typealias ConnectionType = Connection + + private let source: Observable + private let makeSubject: () -> Subject + + fileprivate let lock = RecursiveLock() + fileprivate var subject: Subject? + + // state + fileprivate var connection: ConnectionType? + + init(source: Observable, makeSubject: @escaping () -> Subject) { + self.source = source + self.makeSubject = makeSubject + self.subject = nil + self.connection = nil + } + + override func connect() -> Disposable { + return self.lock.performLocked { + if let connection = self.connection { + return connection + } + + let singleAssignmentDisposable = SingleAssignmentDisposable() + let connection = Connection(parent: self, subjectObserver: self.lazySubject.asObserver(), lock: self.lock, subscription: singleAssignmentDisposable) + self.connection = connection + let subscription = self.source.subscribe(connection) + singleAssignmentDisposable.setDisposable(subscription) + return connection + } + } + + private var lazySubject: Subject { + if let subject = self.subject { + return subject + } + + let subject = self.makeSubject() + self.subject = subject + return subject + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Subject.Element { + self.lazySubject.subscribe(observer) + } +} + +final private class RefCountSink + : Sink + , ObserverType where ConnectableSource.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = RefCount + + private let parent: Parent + + private var connectionIdSnapshot: Int64 = -1 + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = self.parent.source.subscribe(self) + self.parent.lock.lock(); defer { self.parent.lock.unlock() } + + self.connectionIdSnapshot = self.parent.connectionId + + if self.isDisposed { + return Disposables.create() + } + + if self.parent.count == 0 { + self.parent.count = 1 + self.parent.connectableSubscription = self.parent.source.connect() + } + else { + self.parent.count += 1 + } + + return Disposables.create { + subscription.dispose() + self.parent.lock.lock(); defer { self.parent.lock.unlock() } + if self.parent.connectionId != self.connectionIdSnapshot { + return + } + if self.parent.count == 1 { + self.parent.count = 0 + guard let connectableSubscription = self.parent.connectableSubscription else { + return + } + + connectableSubscription.dispose() + self.parent.connectableSubscription = nil + } + else if self.parent.count > 1 { + self.parent.count -= 1 + } + else { + rxFatalError("Something went wrong with RefCount disposing mechanism") + } + } + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .error, .completed: + self.parent.lock.lock() + if self.parent.connectionId == self.connectionIdSnapshot { + let connection = self.parent.connectableSubscription + defer { connection?.dispose() } + self.parent.count = 0 + self.parent.connectionId = self.parent.connectionId &+ 1 + self.parent.connectableSubscription = nil + } + self.parent.lock.unlock() + self.forwardOn(event) + self.dispose() + } + } +} + +final private class RefCount: Producer { + fileprivate let lock = RecursiveLock() + + // state + fileprivate var count = 0 + fileprivate var connectionId: Int64 = 0 + fileprivate var connectableSubscription = nil as Disposable? + + fileprivate let source: ConnectableSource + + init(source: ConnectableSource) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) + where Observer.Element == ConnectableSource.Element { + let sink = RefCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class MulticastSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias ResultType = Element + typealias MutlicastType = Multicast + + private let parent: MutlicastType + + init(parent: MutlicastType, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + do { + let subject = try self.parent.subjectSelector() + let connectable = ConnectableObservableAdapter(source: self.parent.source, makeSubject: { subject }) + + let observable = try self.parent.selector(connectable) + + let subscription = observable.subscribe(self) + let connection = connectable.connect() + + return Disposables.create(subscription, connection) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + return Disposables.create() + } + } + + func on(_ event: Event) { + self.forwardOn(event) + switch event { + case .next: break + case .error, .completed: + self.dispose() + } + } +} + +final private class Multicast: Producer { + typealias SubjectSelectorType = () throws -> Subject + typealias SelectorType = (Observable) throws -> Observable + + fileprivate let source: Observable + fileprivate let subjectSelector: SubjectSelectorType + fileprivate let selector: SelectorType + + init(source: Observable, subjectSelector: @escaping SubjectSelectorType, selector: @escaping SelectorType) { + self.source = source + self.subjectSelector = subjectSelector + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = MulticastSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Never.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Never.swift new file mode 100644 index 000000000..7b456eed9 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Never.swift @@ -0,0 +1,27 @@ +// +// Never.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a non-terminating observable sequence, which can be used to denote an infinite duration. + + - seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: An observable sequence whose observers will never get called. + */ + public static func never() -> Observable { + NeverProducer() + } +} + +final private class NeverProducer: Producer { + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + Disposables.create() + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/ObserveOn.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/ObserveOn.swift new file mode 100644 index 000000000..6b8689e1e --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/ObserveOn.swift @@ -0,0 +1,243 @@ +// +// ObserveOn.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + + This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription + actions have side-effects that require to be run on a scheduler, use `subscribeOn`. + + - seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html) + + - parameter scheduler: Scheduler to notify observers on. + - returns: The source sequence whose observations happen on the specified scheduler. + */ + public func observe(on scheduler: ImmediateSchedulerType) + -> Observable { + guard let serialScheduler = scheduler as? SerialDispatchQueueScheduler else { + return ObserveOn(source: self.asObservable(), scheduler: scheduler) + } + + return ObserveOnSerialDispatchQueue(source: self.asObservable(), + scheduler: serialScheduler) + } + + /** + Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + + This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription + actions have side-effects that require to be run on a scheduler, use `subscribeOn`. + + - seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html) + + - parameter scheduler: Scheduler to notify observers on. + - returns: The source sequence whose observations happen on the specified scheduler. + */ + @available(*, deprecated, renamed: "observe(on:)") + public func observeOn(_ scheduler: ImmediateSchedulerType) + -> Observable { + observe(on: scheduler) + } +} + +final private class ObserveOn: Producer { + let scheduler: ImmediateSchedulerType + let source: Observable + + init(source: Observable, scheduler: ImmediateSchedulerType) { + self.scheduler = scheduler + self.source = source + +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ObserveOnSink(scheduler: self.scheduler, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} + +enum ObserveOnState : Int32 { + // pump is not running + case stopped = 0 + // pump is running + case running = 1 +} + +final private class ObserveOnSink: ObserverBase { + typealias Element = Observer.Element + + let scheduler: ImmediateSchedulerType + + var lock = SpinLock() + let observer: Observer + + // state + var state = ObserveOnState.stopped + var queue = Queue>(capacity: 10) + + let scheduleDisposable = SerialDisposable() + let cancel: Cancelable + + init(scheduler: ImmediateSchedulerType, observer: Observer, cancel: Cancelable) { + self.scheduler = scheduler + self.observer = observer + self.cancel = cancel + } + + override func onCore(_ event: Event) { + let shouldStart = self.lock.performLocked { () -> Bool in + self.queue.enqueue(event) + + switch self.state { + case .stopped: + self.state = .running + return true + case .running: + return false + } + } + + if shouldStart { + self.scheduleDisposable.disposable = self.scheduler.scheduleRecursive((), action: self.run) + } + } + + func run(_ state: (), _ recurse: (()) -> Void) { + let (nextEvent, observer) = self.lock.performLocked { () -> (Event?, Observer) in + if !self.queue.isEmpty { + return (self.queue.dequeue(), self.observer) + } + else { + self.state = .stopped + return (nil, self.observer) + } + } + + if let nextEvent = nextEvent, !self.cancel.isDisposed { + observer.on(nextEvent) + if nextEvent.isStopEvent { + self.dispose() + } + } + else { + return + } + + let shouldContinue = self.shouldContinue_synchronized() + + if shouldContinue { + recurse(()) + } + } + + func shouldContinue_synchronized() -> Bool { + self.lock.performLocked { + let isEmpty = self.queue.isEmpty + if isEmpty { self.state = .stopped } + return !isEmpty + } + } + + override func dispose() { + super.dispose() + + self.cancel.dispose() + self.scheduleDisposable.dispose() + } +} + +#if TRACE_RESOURCES + private let numberOfSerialDispatchObservables = AtomicInt(0) + extension Resources { + /** + Counts number of `SerialDispatchQueueObservables`. + + Purposed for unit tests. + */ + public static var numberOfSerialDispatchQueueObservables: Int32 { + return load(numberOfSerialDispatchObservables) + } + } +#endif + +final private class ObserveOnSerialDispatchQueueSink: ObserverBase { + let scheduler: SerialDispatchQueueScheduler + let observer: Observer + + let cancel: Cancelable + + var cachedScheduleLambda: (((sink: ObserveOnSerialDispatchQueueSink, event: Event)) -> Disposable)! + + init(scheduler: SerialDispatchQueueScheduler, observer: Observer, cancel: Cancelable) { + self.scheduler = scheduler + self.observer = observer + self.cancel = cancel + super.init() + + self.cachedScheduleLambda = { pair in + guard !cancel.isDisposed else { return Disposables.create() } + + pair.sink.observer.on(pair.event) + + if pair.event.isStopEvent { + pair.sink.dispose() + } + + return Disposables.create() + } + } + + override func onCore(_ event: Event) { + _ = self.scheduler.schedule((self, event), action: self.cachedScheduleLambda!) + } + + override func dispose() { + super.dispose() + + self.cancel.dispose() + } +} + +final private class ObserveOnSerialDispatchQueue: Producer { + let scheduler: SerialDispatchQueueScheduler + let source: Observable + + init(source: Observable, scheduler: SerialDispatchQueueScheduler) { + self.scheduler = scheduler + self.source = source + + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + _ = increment(numberOfSerialDispatchObservables) + #endif + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ObserveOnSerialDispatchQueueSink(scheduler: self.scheduler, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + _ = decrement(numberOfSerialDispatchObservables) + } + #endif +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Optional.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Optional.swift new file mode 100644 index 000000000..64f8f1fdd --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Optional.swift @@ -0,0 +1,95 @@ +// +// Optional.swift +// RxSwift +// +// Created by tarunon on 2016/12/13. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + public static func from(optional: Element?) -> Observable { + ObservableOptional(optional: optional) + } + + /** + Converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + - parameter scheduler: Scheduler to send the optional element on. + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + public static func from(optional: Element?, scheduler: ImmediateSchedulerType) -> Observable { + ObservableOptionalScheduled(optional: optional, scheduler: scheduler) + } +} + +final private class ObservableOptionalScheduledSink: Sink { + typealias Element = Observer.Element + typealias Parent = ObservableOptionalScheduled + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.schedule(self.parent.optional) { (optional: Element?) -> Disposable in + if let next = optional { + self.forwardOn(.next(next)) + return self.parent.scheduler.schedule(()) { _ in + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } else { + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } + } +} + +final private class ObservableOptionalScheduled: Producer { + fileprivate let optional: Element? + fileprivate let scheduler: ImmediateSchedulerType + + init(optional: Element?, scheduler: ImmediateSchedulerType) { + self.optional = optional + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ObservableOptionalScheduledSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class ObservableOptional: Producer { + private let optional: Element? + + init(optional: Element?) { + self.optional = optional + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + if let element = self.optional { + observer.on(.next(element)) + } + observer.on(.completed) + return Disposables.create() + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Producer.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Producer.swift new file mode 100644 index 000000000..e611930a5 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Producer.swift @@ -0,0 +1,92 @@ +// +// Producer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class Producer: Observable { + override init() { + super.init() + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + if !CurrentThreadScheduler.isScheduleRequired { + // The returned disposable needs to release all references once it was disposed. + let disposer = SinkDisposer() + let sinkAndSubscription = self.run(observer, cancel: disposer) + disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription) + + return disposer + } + else { + return CurrentThreadScheduler.instance.schedule(()) { _ in + let disposer = SinkDisposer() + let sinkAndSubscription = self.run(observer, cancel: disposer) + disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription) + + return disposer + } + } + } + + func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + rxAbstractMethod() + } +} + +private final class SinkDisposer: Cancelable { + private enum DisposeState: Int32 { + case disposed = 1 + case sinkAndSubscriptionSet = 2 + } + + private let state = AtomicInt(0) + private var sink: Disposable? + private var subscription: Disposable? + + var isDisposed: Bool { + isFlagSet(self.state, DisposeState.disposed.rawValue) + } + + func setSinkAndSubscription(sink: Disposable, subscription: Disposable) { + self.sink = sink + self.subscription = subscription + + let previousState = fetchOr(self.state, DisposeState.sinkAndSubscriptionSet.rawValue) + if (previousState & DisposeState.sinkAndSubscriptionSet.rawValue) != 0 { + rxFatalError("Sink and subscription were already set") + } + + if (previousState & DisposeState.disposed.rawValue) != 0 { + sink.dispose() + subscription.dispose() + self.sink = nil + self.subscription = nil + } + } + + func dispose() { + let previousState = fetchOr(self.state, DisposeState.disposed.rawValue) + + if (previousState & DisposeState.disposed.rawValue) != 0 { + return + } + + if (previousState & DisposeState.sinkAndSubscriptionSet.rawValue) != 0 { + guard let sink = self.sink else { + rxFatalError("Sink not set") + } + guard let subscription = self.subscription else { + rxFatalError("Subscription not set") + } + + sink.dispose() + subscription.dispose() + + self.sink = nil + self.subscription = nil + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Range.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Range.swift new file mode 100644 index 000000000..245353249 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Range.swift @@ -0,0 +1,73 @@ +// +// Range.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where Element: RxAbstractInteger { + /** + Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages. + + - seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html) + + - parameter start: The value of the first integer in the sequence. + - parameter count: The number of sequential integers to generate. + - parameter scheduler: Scheduler to run the generator loop on. + - returns: An observable sequence that contains a range of sequential integral numbers. + */ + public static func range(start: Element, count: Element, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + RangeProducer(start: start, count: count, scheduler: scheduler) + } +} + +final private class RangeProducer: Producer { + fileprivate let start: Element + fileprivate let count: Element + fileprivate let scheduler: ImmediateSchedulerType + + init(start: Element, count: Element, scheduler: ImmediateSchedulerType) { + guard count >= 0 else { + rxFatalError("count can't be negative") + } + + guard start &+ (count - 1) >= start || count == 0 else { + rxFatalError("overflow of count") + } + + self.start = start + self.count = count + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = RangeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class RangeSink: Sink where Observer.Element: RxAbstractInteger { + typealias Parent = RangeProducer + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRecursive(0 as Observer.Element) { i, recurse in + if i < self.parent.count { + self.forwardOn(.next(self.parent.start + i)) + recurse(i + 1) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Reduce.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Reduce.swift new file mode 100644 index 000000000..d5fab3478 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Reduce.swift @@ -0,0 +1,109 @@ +// +// Reduce.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + +extension ObservableType { + /** + Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. + + For aggregation behavior with incremental intermediate results, see `scan`. + + - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: A accumulator function to be invoked on each element. + - parameter mapResult: A function to transform the final accumulator value into the result value. + - returns: An observable sequence containing a single element with the final accumulator value. + */ + public func reduce(_ seed: A, accumulator: @escaping (A, Element) throws -> A, mapResult: @escaping (A) throws -> Result) + -> Observable { + Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: mapResult) + } + + /** + Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. + + For aggregation behavior with incremental intermediate results, see `scan`. + + - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: A accumulator function to be invoked on each element. + - returns: An observable sequence containing a single element with the final accumulator value. + */ + public func reduce(_ seed: A, accumulator: @escaping (A, Element) throws -> A) + -> Observable { + Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: { $0 }) + } +} + +final private class ReduceSink: Sink, ObserverType { + typealias ResultType = Observer.Element + typealias Parent = Reduce + + private let parent: Parent + private var accumulation: AccumulateType + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.accumulation = parent.seed + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + self.accumulation = try self.parent.accumulator(self.accumulation, value) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .error(let e): + self.forwardOn(.error(e)) + self.dispose() + case .completed: + do { + let result = try self.parent.mapResult(self.accumulation) + self.forwardOn(.next(result)) + self.forwardOn(.completed) + self.dispose() + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + } +} + +final private class Reduce: Producer { + typealias AccumulatorType = (AccumulateType, SourceType) throws -> AccumulateType + typealias ResultSelectorType = (AccumulateType) throws -> ResultType + + private let source: Observable + fileprivate let seed: AccumulateType + fileprivate let accumulator: AccumulatorType + fileprivate let mapResult: ResultSelectorType + + init(source: Observable, seed: AccumulateType, accumulator: @escaping AccumulatorType, mapResult: @escaping ResultSelectorType) { + self.source = source + self.seed = seed + self.accumulator = accumulator + self.mapResult = mapResult + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { + let sink = ReduceSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} + diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Repeat.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Repeat.swift new file mode 100644 index 000000000..69a3ba02e --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Repeat.swift @@ -0,0 +1,57 @@ +// +// Repeat.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages. + + - seealso: [repeat operator on reactivex.io](http://reactivex.io/documentation/operators/repeat.html) + + - parameter element: Element to repeat. + - parameter scheduler: Scheduler to run the producer loop on. + - returns: An observable sequence that repeats the given element infinitely. + */ + public static func repeatElement(_ element: Element, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + RepeatElement(element: element, scheduler: scheduler) + } +} + +final private class RepeatElement: Producer { + fileprivate let element: Element + fileprivate let scheduler: ImmediateSchedulerType + + init(element: Element, scheduler: ImmediateSchedulerType) { + self.element = element + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = RepeatElementSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + + return (sink: sink, subscription: subscription) + } +} + +final private class RepeatElementSink: Sink { + typealias Parent = RepeatElement + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRecursive(self.parent.element) { e, recurse in + self.forwardOn(.next(e)) + recurse(e) + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/RetryWhen.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/RetryWhen.swift new file mode 100644 index 000000000..1b2a6f132 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/RetryWhen.swift @@ -0,0 +1,211 @@ +// +// RetryWhen.swift +// RxSwift +// +// Created by Junior B. on 06/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + public func retry(when notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + @available(*, deprecated, renamed: "retry(when:)") + public func retryWhen(_ notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + retry(when: notificationHandler) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + public func retry(when notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + @available(*, deprecated, renamed: "retry(when:)") + public func retryWhen(_ notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } +} + +final private class RetryTriggerSink + : ObserverType where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element { + typealias Element = TriggerObservable.Element + + typealias Parent = RetryWhenSequenceSinkIter + + private let parent: Parent + + init(parent: Parent) { + self.parent = parent + } + + func on(_ event: Event) { + switch event { + case .next: + self.parent.parent.lastError = nil + self.parent.parent.schedule(.moveNext) + case .error(let e): + self.parent.parent.forwardOn(.error(e)) + self.parent.parent.dispose() + case .completed: + self.parent.parent.forwardOn(.completed) + self.parent.parent.dispose() + } + } +} + +final private class RetryWhenSequenceSinkIter + : ObserverType + , Disposable where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = RetryWhenSequenceSink + + fileprivate let parent: Parent + private let errorHandlerSubscription = SingleAssignmentDisposable() + private let subscription: Disposable + + init(parent: Parent, subscription: Disposable) { + self.parent = parent + self.subscription = subscription + } + + func on(_ event: Event) { + switch event { + case .next: + self.parent.forwardOn(event) + case .error(let error): + self.parent.lastError = error + + if let failedWith = error as? Error { + // dispose current subscription + self.subscription.dispose() + + let errorHandlerSubscription = self.parent.notifier.subscribe(RetryTriggerSink(parent: self)) + self.errorHandlerSubscription.setDisposable(errorHandlerSubscription) + self.parent.errorSubject.on(.next(failedWith)) + } + else { + self.parent.forwardOn(.error(error)) + self.parent.dispose() + } + case .completed: + self.parent.forwardOn(event) + self.parent.dispose() + } + } + + final func dispose() { + self.subscription.dispose() + self.errorHandlerSubscription.dispose() + } +} + +final private class RetryWhenSequenceSink + : TailRecursiveSink where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = RetryWhenSequence + + let lock = RecursiveLock() + + private let parent: Parent + + fileprivate var lastError: Swift.Error? + fileprivate let errorSubject = PublishSubject() + private let handler: Observable + fileprivate let notifier = PublishSubject() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.handler = parent.notificationHandler(self.errorSubject).asObservable() + super.init(observer: observer, cancel: cancel) + } + + override func done() { + if let lastError = self.lastError { + self.forwardOn(.error(lastError)) + self.lastError = nil + } + else { + self.forwardOn(.completed) + } + + self.dispose() + } + + override func extract(_ observable: Observable) -> SequenceGenerator? { + // It is important to always return `nil` here because there are side effects in the `run` method + // that are dependant on particular `retryWhen` operator so single operator stack can't be reused in this + // case. + return nil + } + + override func subscribeToNext(_ source: Observable) -> Disposable { + let subscription = SingleAssignmentDisposable() + let iter = RetryWhenSequenceSinkIter(parent: self, subscription: subscription) + subscription.setDisposable(source.subscribe(iter)) + return iter + } + + override func run(_ sources: SequenceGenerator) -> Disposable { + let triggerSubscription = self.handler.subscribe(self.notifier.asObserver()) + let superSubscription = super.run(sources) + return Disposables.create(superSubscription, triggerSubscription) + } +} + +final private class RetryWhenSequence: Producer where Sequence.Element: ObservableType { + typealias Element = Sequence.Element.Element + + private let sources: Sequence + fileprivate let notificationHandler: (Observable) -> TriggerObservable + + init(sources: Sequence, notificationHandler: @escaping (Observable) -> TriggerObservable) { + self.sources = sources + self.notificationHandler = notificationHandler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = RetryWhenSequenceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run((self.sources.makeIterator(), nil)) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Sample.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Sample.swift new file mode 100644 index 000000000..9301c9af7 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Sample.swift @@ -0,0 +1,139 @@ +// +// Sample.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Samples the source observable sequence using a sampler observable sequence producing sampling ticks. + + Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence. + + **In case there were no new elements between sampler ticks, you may provide a default value to be emitted, instead + to the resulting sequence otherwise no element is sent.** + + - seealso: [sample operator on reactivex.io](http://reactivex.io/documentation/operators/sample.html) + + - parameter sampler: Sampling tick sequence. + - parameter defaultValue: a value to return if there are no new elements between sampler ticks + - returns: Sampled observable sequence. + */ + public func sample(_ sampler: Source, defaultValue: Element? = nil) + -> Observable { + return Sample(source: self.asObservable(), sampler: sampler.asObservable(), defaultValue: defaultValue) + } +} + +final private class SamplerSink + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = SampleType + + typealias Parent = SampleSequenceSink + + private let parent: Parent + + var lock: RecursiveLock { + self.parent.lock + } + + init(parent: Parent) { + self.parent = parent + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next, .completed: + if let element = parent.element ?? self.parent.defaultValue { + self.parent.element = nil + self.parent.forwardOn(.next(element)) + } + + if self.parent.atEnd { + self.parent.forwardOn(.completed) + self.parent.dispose() + } + case .error(let e): + self.parent.forwardOn(.error(e)) + self.parent.dispose() + } + } +} + +final private class SampleSequenceSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias Parent = Sample + + fileprivate let parent: Parent + fileprivate let defaultValue: Element? + + let lock = RecursiveLock() + + // state + fileprivate var element = nil as Element? + fileprivate var atEnd = false + + private let sourceSubscription = SingleAssignmentDisposable() + + init(parent: Parent, observer: Observer, cancel: Cancelable, defaultValue: Element? = nil) { + self.parent = parent + self.defaultValue = defaultValue + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + self.sourceSubscription.setDisposable(self.parent.source.subscribe(self)) + let samplerSubscription = self.parent.sampler.subscribe(SamplerSink(parent: self)) + + return Disposables.create(sourceSubscription, samplerSubscription) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let element): + self.element = element + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.atEnd = true + self.sourceSubscription.dispose() + } + } + +} + +final private class Sample: Producer { + fileprivate let source: Observable + fileprivate let sampler: Observable + fileprivate let defaultValue: Element? + + init(source: Observable, sampler: Observable, defaultValue: Element? = nil) { + self.source = source + self.sampler = sampler + self.defaultValue = defaultValue + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SampleSequenceSink(parent: self, observer: observer, cancel: cancel, defaultValue: self.defaultValue) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Scan.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Scan.swift new file mode 100644 index 000000000..ecf69c80c --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Scan.swift @@ -0,0 +1,100 @@ +// +// Scan.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. + + For aggregation behavior with no intermediate results, see `reduce`. + + - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: An accumulator function to be invoked on each element. + - returns: An observable sequence containing the accumulated values. + */ + public func scan(into seed: A, accumulator: @escaping (inout A, Element) throws -> Void) + -> Observable { + Scan(source: self.asObservable(), seed: seed, accumulator: accumulator) + } + + /** + Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. + + For aggregation behavior with no intermediate results, see `reduce`. + + - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: An accumulator function to be invoked on each element. + - returns: An observable sequence containing the accumulated values. + */ + public func scan(_ seed: A, accumulator: @escaping (A, Element) throws -> A) + -> Observable { + return Scan(source: self.asObservable(), seed: seed) { acc, element in + let currentAcc = acc + acc = try accumulator(currentAcc, element) + } + } +} + +final private class ScanSink: Sink, ObserverType { + typealias Accumulate = Observer.Element + typealias Parent = Scan + + private let parent: Parent + private var accumulate: Accumulate + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.accumulate = parent.seed + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let element): + do { + try self.parent.accumulator(&self.accumulate, element) + self.forwardOn(.next(self.accumulate)) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } + +} + +final private class Scan: Producer { + typealias Accumulator = (inout Accumulate, Element) throws -> Void + + private let source: Observable + fileprivate let seed: Accumulate + fileprivate let accumulator: Accumulator + + init(source: Observable, seed: Accumulate, accumulator: @escaping Accumulator) { + self.source = source + self.seed = seed + self.accumulator = accumulator + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Accumulate { + let sink = ScanSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Sequence.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Sequence.swift new file mode 100644 index 000000000..c6d10896e --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Sequence.swift @@ -0,0 +1,89 @@ +// +// Sequence.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + // MARK: of + + /** + This method creates a new Observable instance with a variable number of elements. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter elements: Elements to generate. + - parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediately on subscription. + - returns: The observable sequence whose elements are pulled from the given arguments. + */ + public static func of(_ elements: Element ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + ObservableSequence(elements: elements, scheduler: scheduler) + } +} + +extension ObservableType { + /** + 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: [Element], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + 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: Sequence, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable where Sequence.Element == Element { + ObservableSequence(elements: sequence, scheduler: scheduler) + } +} + +final private class ObservableSequenceSink: Sink where Sequence.Element == Observer.Element { + typealias Parent = ObservableSequence + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRecursive(self.parent.elements.makeIterator()) { iterator, recurse in + var mutableIterator = iterator + if let next = mutableIterator.next() { + self.forwardOn(.next(next)) + recurse(mutableIterator) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + } +} + +final private class ObservableSequence: Producer { + fileprivate let elements: Sequence + fileprivate let scheduler: ImmediateSchedulerType + + init(elements: Sequence, scheduler: ImmediateSchedulerType) { + self.elements = elements + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ObservableSequenceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/ShareReplayScope.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/ShareReplayScope.swift new file mode 100644 index 000000000..59d440dc3 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/ShareReplayScope.swift @@ -0,0 +1,443 @@ +// +// ShareReplayScope.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/28/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +/// Subject lifetime scope +public enum SubjectLifetimeScope { + /** + **Each connection will have it's own subject instance to store replay events.** + **Connections will be isolated from each another.** + + Configures the underlying implementation to behave equivalent to. + + ``` + source.multicast(makeSubject: { MySubject() }).refCount() + ``` + + **This is the recommended default.** + + This has the following consequences: + * `retry` or `concat` operators will function as expected because terminating the sequence will clear internal state. + * Each connection to source observable sequence will use it's own subject. + * When the number of subscribers drops from 1 to 0 and connection to source sequence is disposed, subject will be cleared. + + + ``` + let xs = Observable.deferred { () -> Observable in + print("Performing work ...") + return Observable.just(Date().timeIntervalSince1970) + } + .share(replay: 1, scope: .whileConnected) + + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + + ``` + + Notice how time interval is different and `Performing work ...` is printed each time) + + ``` + Performing work ... + next 1495998900.82141 + completed + + Performing work ... + next 1495998900.82359 + completed + + Performing work ... + next 1495998900.82444 + completed + + + ``` + + */ + case whileConnected + + /** + **One subject will store replay events for all connections to source.** + **Connections won't be isolated from each another.** + + Configures the underlying implementation behave equivalent to. + + ``` + source.multicast(MySubject()).refCount() + ``` + + This has the following consequences: + * Using `retry` or `concat` operators after this operator usually isn't advised. + * Each connection to source observable sequence will share the same subject. + * After number of subscribers drops from 1 to 0 and connection to source observable sequence is dispose, this operator will + continue holding a reference to the same subject. + If at some later moment a new observer initiates a new connection to source it can potentially receive + some of the stale events received during previous connection. + * After source sequence terminates any new observer will always immediately receive replayed elements and terminal event. + No new subscriptions to source observable sequence will be attempted. + + ``` + let xs = Observable.deferred { () -> Observable in + print("Performing work ...") + return Observable.just(Date().timeIntervalSince1970) + } + .share(replay: 1, scope: .forever) + + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + ``` + + Notice how time interval is the same, replayed, and `Performing work ...` is printed only once + + ``` + Performing work ... + next 1495999013.76356 + completed + + next 1495999013.76356 + completed + + next 1495999013.76356 + completed + ``` + + */ + case forever +} + +extension ObservableType { + + /** + Returns an observable sequence that **shares a single subscription to the underlying sequence**, and immediately upon subscription replays elements in buffer. + + This operator is equivalent to: + * `.whileConnected` + ``` + // Each connection will have it's own subject instance to store replay events. + // Connections will be isolated from each another. + source.multicast(makeSubject: { Replay.create(bufferSize: replay) }).refCount() + ``` + * `.forever` + ``` + // One subject will store replay events for all connections to source. + // Connections won't be isolated from each another. + source.multicast(Replay.create(bufferSize: replay)).refCount() + ``` + + It uses optimized versions of the operators for most common operations. + + - parameter replay: Maximum element count of the replay buffer. + - parameter scope: Lifetime scope of sharing subject. For more information see `SubjectLifetimeScope` enum. + + - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected) + -> Observable { + switch scope { + case .forever: + switch replay { + case 0: return self.multicast(PublishSubject()).refCount() + default: return self.multicast(ReplaySubject.create(bufferSize: replay)).refCount() + } + case .whileConnected: + switch replay { + case 0: return ShareWhileConnected(source: self.asObservable()) + case 1: return ShareReplay1WhileConnected(source: self.asObservable()) + default: return self.multicast(makeSubject: { ReplaySubject.create(bufferSize: replay) }).refCount() + } + } + } +} + +private final class ShareReplay1WhileConnectedConnection + : ObserverType + , SynchronizedUnsubscribeType { + typealias Observers = AnyObserver.s + typealias DisposeKey = Observers.KeyType + + typealias Parent = ShareReplay1WhileConnected + private let parent: Parent + private let subscription = SingleAssignmentDisposable() + + private let lock: RecursiveLock + private var disposed: Bool = false + fileprivate var observers = Observers() + private var element: Element? + + init(parent: Parent, lock: RecursiveLock) { + self.parent = parent + self.lock = lock + + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + final func on(_ event: Event) { + let observers = self.lock.performLocked { self.synchronized_on(event) } + dispatch(observers, event) + } + + final private func synchronized_on(_ event: Event) -> Observers { + if self.disposed { + return Observers() + } + + switch event { + case .next(let element): + self.element = element + return self.observers + case .error, .completed: + let observers = self.observers + self.synchronized_dispose() + return observers + } + } + + final func connect() { + self.subscription.setDisposable(self.parent.source.subscribe(self)) + } + + final func synchronized_subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.lock.performLocked { + if let element = self.element { + observer.on(.next(element)) + } + + let disposeKey = self.observers.insert(observer.on) + + return SubscriptionDisposable(owner: self, key: disposeKey) + } + } + + final private func synchronized_dispose() { + self.disposed = true + if self.parent.connection === self { + self.parent.connection = nil + } + self.observers = Observers() + } + + final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { + if self.lock.performLocked({ self.synchronized_unsubscribe(disposeKey) }) { + self.subscription.dispose() + } + } + + @inline(__always) + final private func synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { + // if already unsubscribed, just return + if self.observers.removeKey(disposeKey) == nil { + return false + } + + if self.observers.count == 0 { + self.synchronized_dispose() + return true + } + + return false + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif +} + +// optimized version of share replay for most common case +final private class ShareReplay1WhileConnected + : Observable { + + fileprivate typealias Connection = ShareReplay1WhileConnectedConnection + + fileprivate let source: Observable + + private let lock = RecursiveLock() + + fileprivate var connection: Connection? + + init(source: Observable) { + self.source = source + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.lock.lock() + let connection = self.synchronized_subscribe(observer) + let count = connection.observers.count + + let disposable = connection.synchronized_subscribe(observer) + self.lock.unlock() + + if count == 0 { + connection.connect() + } + + return disposable + } + + @inline(__always) + private func synchronized_subscribe(_ observer: Observer) -> Connection where Observer.Element == Element { + let connection: Connection + + if let existingConnection = self.connection { + connection = existingConnection + } + else { + connection = ShareReplay1WhileConnectedConnection( + parent: self, + lock: self.lock) + self.connection = connection + } + + return connection + } +} + +private final class ShareWhileConnectedConnection + : ObserverType + , SynchronizedUnsubscribeType { + typealias Observers = AnyObserver.s + typealias DisposeKey = Observers.KeyType + + typealias Parent = ShareWhileConnected + private let parent: Parent + private let subscription = SingleAssignmentDisposable() + + private let lock: RecursiveLock + private var disposed: Bool = false + fileprivate var observers = Observers() + + init(parent: Parent, lock: RecursiveLock) { + self.parent = parent + self.lock = lock + + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + final func on(_ event: Event) { + let observers = self.lock.performLocked { self.synchronized_on(event) } + dispatch(observers, event) + } + + final private func synchronized_on(_ event: Event) -> Observers { + if self.disposed { + return Observers() + } + + switch event { + case .next: + return self.observers + case .error, .completed: + let observers = self.observers + self.synchronized_dispose() + return observers + } + } + + final func connect() { + self.subscription.setDisposable(self.parent.source.subscribe(self)) + } + + final func synchronized_subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.lock.performLocked { + let disposeKey = self.observers.insert(observer.on) + + return SubscriptionDisposable(owner: self, key: disposeKey) + } + } + + final private func synchronized_dispose() { + self.disposed = true + if self.parent.connection === self { + self.parent.connection = nil + } + self.observers = Observers() + } + + final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { + if self.lock.performLocked({ self.synchronized_unsubscribe(disposeKey) }) { + self.subscription.dispose() + } + } + + @inline(__always) + final private func synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { + // if already unsubscribed, just return + if self.observers.removeKey(disposeKey) == nil { + return false + } + + if self.observers.count == 0 { + self.synchronized_dispose() + return true + } + + return false + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif +} + +// optimized version of share replay for most common case +final private class ShareWhileConnected + : Observable { + + fileprivate typealias Connection = ShareWhileConnectedConnection + + fileprivate let source: Observable + + private let lock = RecursiveLock() + + fileprivate var connection: Connection? + + init(source: Observable) { + self.source = source + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.lock.lock() + let connection = self.synchronized_subscribe(observer) + let count = connection.observers.count + + let disposable = connection.synchronized_subscribe(observer) + self.lock.unlock() + + if count == 0 { + connection.connect() + } + + return disposable + } + + @inline(__always) + private func synchronized_subscribe(_ observer: Observer) -> Connection where Observer.Element == Element { + let connection: Connection + + if let existingConnection = self.connection { + connection = existingConnection + } + else { + connection = ShareWhileConnectedConnection( + parent: self, + lock: self.lock) + self.connection = connection + } + + return connection + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SingleAsync.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SingleAsync.swift new file mode 100644 index 000000000..04e221764 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SingleAsync.swift @@ -0,0 +1,104 @@ +// +// SingleAsync.swift +// RxSwift +// +// Created by Junior B. on 09/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + The single operator is similar to first, but throws a `RxError.noElements` or `RxError.moreThanOneElement` + if the source Observable does not emit exactly one element before successfully completing. + + - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) + + - returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted. + */ + public func single() + -> Observable { + SingleAsync(source: self.asObservable()) + } + + /** + The single operator is similar to first, but throws a `RxError.NoElements` or `RxError.MoreThanOneElement` + if the source Observable does not emit exactly one element before successfully completing. + + - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted. + */ + public func single(_ predicate: @escaping (Element) throws -> Bool) + -> Observable { + SingleAsync(source: self.asObservable(), predicate: predicate) + } +} + +private final class SingleAsyncSink : Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = SingleAsync + + private let parent: Parent + private var seenValue: Bool = false + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let forward = try self.parent.predicate?(value) ?? true + if !forward { + return + } + } + catch let error { + self.forwardOn(.error(error as Swift.Error)) + self.dispose() + return + } + + if self.seenValue { + self.forwardOn(.error(RxError.moreThanOneElement)) + self.dispose() + return + } + + self.seenValue = true + self.forwardOn(.next(value)) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if self.seenValue { + self.forwardOn(.completed) + } else { + self.forwardOn(.error(RxError.noElements)) + } + self.dispose() + } + } +} + +final class SingleAsync: Producer { + typealias Predicate = (Element) throws -> Bool + + private let source: Observable + fileprivate let predicate: Predicate? + + init(source: Observable, predicate: Predicate? = nil) { + self.source = source + self.predicate = predicate + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SingleAsyncSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Sink.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Sink.swift new file mode 100644 index 000000000..ed4fec01e --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Sink.swift @@ -0,0 +1,75 @@ +// +// Sink.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class Sink: Disposable { + fileprivate let observer: Observer + fileprivate let cancel: Cancelable + private let disposed = AtomicInt(0) + + #if DEBUG + private let synchronizationTracker = SynchronizationTracker() + #endif + + init(observer: Observer, cancel: Cancelable) { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + self.observer = observer + self.cancel = cancel + } + + final func forwardOn(_ event: Event) { + #if DEBUG + self.synchronizationTracker.register(synchronizationErrorMessage: .default) + defer { self.synchronizationTracker.unregister() } + #endif + if isFlagSet(self.disposed, 1) { + return + } + self.observer.on(event) + } + + final func forwarder() -> SinkForward { + SinkForward(forward: self) + } + + final var isDisposed: Bool { + isFlagSet(self.disposed, 1) + } + + func dispose() { + fetchOr(self.disposed, 1) + self.cancel.dispose() + } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} + +final class SinkForward: ObserverType { + typealias Element = Observer.Element + + private let forward: Sink + + init(forward: Sink) { + self.forward = forward + } + + final func on(_ event: Event) { + switch event { + case .next: + self.forward.observer.on(event) + case .error, .completed: + self.forward.observer.on(event) + self.forward.cancel.dispose() + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Skip.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Skip.swift new file mode 100644 index 000000000..5856f3744 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Skip.swift @@ -0,0 +1,158 @@ +// +// Skip.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter count: The number of elements to skip before returning the remaining elements. + - returns: An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + public func skip(_ count: Int) + -> Observable { + SkipCount(source: self.asObservable(), count: count) + } +} + +extension ObservableType { + + /** + Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter duration: Duration for skipping elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + public func skip(_ duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler) + } +} + +// count version + +final private class SkipCountSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = SkipCount + + let parent: Parent + + var remaining: Int + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.remaining = parent.count + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + + if self.remaining <= 0 { + self.forwardOn(.next(value)) + } + else { + self.remaining -= 1 + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + +} + +final private class SkipCount: Producer { + let source: Observable + let count: Int + + init(source: Observable, count: Int) { + self.source = source + self.count = count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SkipCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + + return (sink: sink, subscription: subscription) + } +} + +// time version + +final private class SkipTimeSink: Sink, ObserverType where Observer.Element == Element { + typealias Parent = SkipTime + + let parent: Parent + + // state + var open = false + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if self.open { + self.forwardOn(.next(value)) + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + func tick() { + self.open = true + } + + func run() -> Disposable { + let disposeTimer = self.parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { _ in + self.tick() + return Disposables.create() + } + + let disposeSubscription = self.parent.source.subscribe(self) + + return Disposables.create(disposeTimer, disposeSubscription) + } +} + +final private class SkipTime: Producer { + let source: Observable + let duration: RxTimeInterval + let scheduler: SchedulerType + + init(source: Observable, duration: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.scheduler = scheduler + self.duration = duration + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SkipTimeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SkipUntil.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SkipUntil.swift new file mode 100644 index 000000000..c8fe19340 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SkipUntil.swift @@ -0,0 +1,152 @@ +// +// SkipUntil.swift +// RxSwift +// +// Created by Yury Korolev on 10/3/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns the elements from the source observable sequence that are emitted after the other observable sequence produces an element. + + - seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html) + + - parameter other: Observable sequence that starts propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence that are emitted after the other sequence emits an item. + */ + public func skip(until other: Source) + -> Observable { + SkipUntil(source: self.asObservable(), other: other.asObservable()) + } + + /** + Returns the elements from the source observable sequence that are emitted after the other observable sequence produces an element. + + - seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html) + + - parameter other: Observable sequence that starts propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence that are emitted after the other sequence emits an item. + */ + @available(*, deprecated, renamed: "skip(until:)") + public func skipUntil(_ other: Source) + -> Observable { + skip(until: other) + } +} + +final private class SkipUntilSinkOther + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = SkipUntilSink + typealias Element = Other + + private let parent: Parent + + var lock: RecursiveLock { + self.parent.lock + } + + let subscription = SingleAssignmentDisposable() + + init(parent: Parent) { + self.parent = parent + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + self.parent.forwardElements = true + self.subscription.dispose() + case .error(let e): + self.parent.forwardOn(.error(e)) + self.parent.dispose() + case .completed: + self.subscription.dispose() + } + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif + +} + + +final private class SkipUntilSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias Parent = SkipUntil + + let lock = RecursiveLock() + private let parent: Parent + fileprivate var forwardElements = false + + private let sourceSubscription = SingleAssignmentDisposable() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + if self.forwardElements { + self.forwardOn(event) + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if self.forwardElements { + self.forwardOn(event) + } + self.dispose() + } + } + + func run() -> Disposable { + let sourceSubscription = self.parent.source.subscribe(self) + let otherObserver = SkipUntilSinkOther(parent: self) + let otherSubscription = self.parent.other.subscribe(otherObserver) + self.sourceSubscription.setDisposable(sourceSubscription) + otherObserver.subscription.setDisposable(otherSubscription) + + return Disposables.create(sourceSubscription, otherObserver.subscription) + } +} + +final private class SkipUntil: Producer { + + fileprivate let source: Observable + fileprivate let other: Observable + + init(source: Observable, other: Observable) { + self.source = source + self.other = other + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SkipUntilSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SkipWhile.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SkipWhile.swift new file mode 100644 index 000000000..a62f88ddd --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SkipWhile.swift @@ -0,0 +1,87 @@ +// +// SkipWhile.swift +// RxSwift +// +// Created by Yury Korolev on 10/9/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + + - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + public func skip(while predicate: @escaping (Element) throws -> Bool) -> Observable { + SkipWhile(source: self.asObservable(), predicate: predicate) + } + + /** + Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + + - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + @available(*, deprecated, renamed: "skip(while:)") + public func skipWhile(_ predicate: @escaping (Element) throws -> Bool) -> Observable { + SkipWhile(source: self.asObservable(), predicate: predicate) + } +} + +final private class SkipWhileSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = SkipWhile + + private let parent: Parent + private var running = false + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if !self.running { + do { + self.running = try !self.parent.predicate(value) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + return + } + } + + if self.running { + self.forwardOn(.next(value)) + } + case .error, .completed: + self.forwardOn(event) + self.dispose() + } + } +} + +final private class SkipWhile: Producer { + typealias Predicate = (Element) throws -> Bool + + private let source: Observable + fileprivate let predicate: Predicate + + init(source: Observable, predicate: @escaping Predicate) { + self.source = source + self.predicate = predicate + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SkipWhileSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/StartWith.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/StartWith.swift new file mode 100644 index 000000000..13fb31d33 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/StartWith.swift @@ -0,0 +1,42 @@ +// +// StartWith.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Prepends a sequence of values to an observable sequence. + + - seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html) + + - parameter elements: Elements to prepend to the specified sequence. + - returns: The source sequence prepended with the specified values. + */ + public func startWith(_ elements: Element ...) + -> Observable { + return StartWith(source: self.asObservable(), elements: elements) + } +} + +final private class StartWith: Producer { + let elements: [Element] + let source: Observable + + init(source: Observable, elements: [Element]) { + self.source = source + self.elements = elements + super.init() + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + for e in self.elements { + observer.on(.next(e)) + } + + return (sink: Disposables.create(), subscription: self.source.subscribe(observer)) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SubscribeOn.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SubscribeOn.swift new file mode 100644 index 000000000..e8e41d9cf --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SubscribeOn.swift @@ -0,0 +1,103 @@ +// +// SubscribeOn.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Wraps the source sequence in order to run its subscription and unsubscription logic on the specified + scheduler. + + This operation is not commonly used. + + This only performs the side-effects of subscription and unsubscription on the specified scheduler. + + In order to invoke observer callbacks on a `scheduler`, use `observeOn`. + + - seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html) + + - parameter scheduler: Scheduler to perform subscription and unsubscription actions on. + - returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + public func subscribe(on scheduler: ImmediateSchedulerType) + -> Observable { + SubscribeOn(source: self, scheduler: scheduler) + } + + /** + Wraps the source sequence in order to run its subscription and unsubscription logic on the specified + scheduler. + + This operation is not commonly used. + + This only performs the side-effects of subscription and unsubscription on the specified scheduler. + + In order to invoke observer callbacks on a `scheduler`, use `observeOn`. + + - seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html) + + - parameter scheduler: Scheduler to perform subscription and unsubscription actions on. + - returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + @available(*, deprecated, renamed: "subscribe(on:)") + public func subscribeOn(_ scheduler: ImmediateSchedulerType) + -> Observable { + subscribe(on: scheduler) + } +} + +final private class SubscribeOnSink: Sink, ObserverType where Ob.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = SubscribeOn + + let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.forwardOn(event) + + if event.isStopEvent { + self.dispose() + } + } + + func run() -> Disposable { + let disposeEverything = SerialDisposable() + let cancelSchedule = SingleAssignmentDisposable() + + disposeEverything.disposable = cancelSchedule + + let disposeSchedule = self.parent.scheduler.schedule(()) { _ -> Disposable in + let subscription = self.parent.source.subscribe(self) + disposeEverything.disposable = ScheduledDisposable(scheduler: self.parent.scheduler, disposable: subscription) + return Disposables.create() + } + + cancelSchedule.setDisposable(disposeSchedule) + + return disposeEverything + } +} + +final private class SubscribeOn: Producer { + let source: Ob + let scheduler: ImmediateSchedulerType + + init(source: Ob, scheduler: ImmediateSchedulerType) { + self.source = source + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Ob.Element { + let sink = SubscribeOnSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Switch.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Switch.swift new file mode 100644 index 000000000..5aa60b97a --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Switch.swift @@ -0,0 +1,251 @@ +// +// Switch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Projects each element of an observable sequence into a new sequence of observable sequences and then + transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + + It is a combination of `map` + `switchLatest` operator + + - seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an + Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func flatMapLatest(_ selector: @escaping (Element) throws -> Source) + -> Observable { + return FlatMapLatest(source: self.asObservable(), selector: selector) + } + + /** + Projects each element of an observable sequence into a new sequence of observable sequences and then + transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + + It is a combination of `map` + `switchLatest` operator + + - seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an + Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func flatMapLatest(_ selector: @escaping (Element) throws -> Source) + -> Infallible { + return Infallible(flatMapLatest(selector)) + } +} + +extension ObservableType where Element: ObservableConvertibleType { + + /** + Transforms an observable sequence of observable sequences into an observable sequence + producing values only from the most recent observable sequence. + + Each time a new inner observable sequence is received, unsubscribe from the + previous inner observable sequence. + + - seealso: [switch operator on reactivex.io](http://reactivex.io/documentation/operators/switch.html) + + - returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func switchLatest() -> Observable { + Switch(source: self.asObservable()) + } +} + +private class SwitchSink + : Sink + , ObserverType where Source.Element == Observer.Element { + typealias Element = SourceType + + private let subscriptions: SingleAssignmentDisposable = SingleAssignmentDisposable() + private let innerSubscription: SerialDisposable = SerialDisposable() + + let lock = RecursiveLock() + + // state + fileprivate var stopped = false + fileprivate var latest = 0 + fileprivate var hasLatest = false + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + let subscription = source.subscribe(self) + self.subscriptions.setDisposable(subscription) + return Disposables.create(subscriptions, innerSubscription) + } + + func performMap(_ element: SourceType) throws -> Source { + rxAbstractMethod() + } + + @inline(__always) + final private func nextElementArrived(element: Element) -> (Int, Observable)? { + self.lock.lock(); defer { self.lock.unlock() } + + do { + let observable = try self.performMap(element).asObservable() + self.hasLatest = true + self.latest = self.latest &+ 1 + return (self.latest, observable) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + + return nil + } + + func on(_ event: Event) { + switch event { + case .next(let element): + if let (latest, observable) = self.nextElementArrived(element: element) { + let d = SingleAssignmentDisposable() + self.innerSubscription.disposable = d + + let observer = SwitchSinkIter(parent: self, id: latest, this: d) + let disposable = observable.subscribe(observer) + d.setDisposable(disposable) + } + case .error(let error): + self.lock.lock(); defer { self.lock.unlock() } + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.lock.lock(); defer { self.lock.unlock() } + self.stopped = true + + self.subscriptions.dispose() + + if !self.hasLatest { + self.forwardOn(.completed) + self.dispose() + } + } + } +} + +final private class SwitchSinkIter + : ObserverType + , LockOwnerType + , SynchronizedOnType where Source.Element == Observer.Element { + typealias Element = Source.Element + typealias Parent = SwitchSink + + private let parent: Parent + private let id: Int + private let this: Disposable + + var lock: RecursiveLock { + self.parent.lock + } + + init(parent: Parent, id: Int, this: Disposable) { + self.parent = parent + self.id = id + self.this = this + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: break + case .error, .completed: + self.this.dispose() + } + + if self.parent.latest != self.id { + return + } + + switch event { + case .next: + self.parent.forwardOn(event) + case .error: + self.parent.forwardOn(event) + self.parent.dispose() + case .completed: + self.parent.hasLatest = false + if self.parent.stopped { + self.parent.forwardOn(event) + self.parent.dispose() + } + } + } +} + +// MARK: Specializations + +final private class SwitchIdentitySink: SwitchSink + where Observer.Element == Source.Element { + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: Source) throws -> Source { + element + } +} + +final private class MapSwitchSink: SwitchSink where Observer.Element == Source.Element { + typealias Selector = (SourceType) throws -> Source + + private let selector: Selector + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self.selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceType) throws -> Source { + try self.selector(element) + } +} + +// MARK: Producers + +final private class Switch: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Source.Element { + let sink = SwitchIdentitySink(observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final private class FlatMapLatest: Producer { + typealias Selector = (SourceType) throws -> Source + + private let source: Observable + private let selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Source.Element { + let sink = MapSwitchSink(selector: self.selector, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SwitchIfEmpty.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SwitchIfEmpty.swift new file mode 100644 index 000000000..037bf6970 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/SwitchIfEmpty.swift @@ -0,0 +1,104 @@ +// +// SwitchIfEmpty.swift +// RxSwift +// +// Created by sergdort on 23/12/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns the elements of the specified sequence or `switchTo` sequence if the sequence is empty. + + - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) + + - parameter other: Observable sequence being returned when source sequence is empty. + - returns: Observable sequence that contains elements from switchTo sequence if source is empty, otherwise returns source sequence elements. + */ + public func ifEmpty(switchTo other: Observable) -> Observable { + SwitchIfEmpty(source: self.asObservable(), ifEmpty: other) + } +} + +final private class SwitchIfEmpty: Producer { + + private let source: Observable + private let ifEmpty: Observable + + init(source: Observable, ifEmpty: Observable) { + self.source = source + self.ifEmpty = ifEmpty + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SwitchIfEmptySink(ifEmpty: self.ifEmpty, + observer: observer, + cancel: cancel) + let subscription = sink.run(self.source.asObservable()) + + return (sink: sink, subscription: subscription) + } +} + +final private class SwitchIfEmptySink: Sink + , ObserverType { + typealias Element = Observer.Element + + private let ifEmpty: Observable + private var isEmpty = true + private let ifEmptySubscription = SingleAssignmentDisposable() + + init(ifEmpty: Observable, observer: Observer, cancel: Cancelable) { + self.ifEmpty = ifEmpty + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + let subscription = source.subscribe(self) + return Disposables.create(subscription, ifEmptySubscription) + } + + func on(_ event: Event) { + switch event { + case .next: + self.isEmpty = false + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + guard self.isEmpty else { + self.forwardOn(.completed) + self.dispose() + return + } + let ifEmptySink = SwitchIfEmptySinkIter(parent: self) + self.ifEmptySubscription.setDisposable(self.ifEmpty.subscribe(ifEmptySink)) + } + } +} + +final private class SwitchIfEmptySinkIter + : ObserverType { + typealias Element = Observer.Element + typealias Parent = SwitchIfEmptySink + + private let parent: Parent + + init(parent: Parent) { + self.parent = parent + } + + func on(_ event: Event) { + switch event { + case .next: + self.parent.forwardOn(event) + case .error: + self.parent.forwardOn(event) + self.parent.dispose() + case .completed: + self.parent.forwardOn(event) + self.parent.dispose() + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Take.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Take.swift new file mode 100644 index 000000000..e5746880f --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Take.swift @@ -0,0 +1,193 @@ +// +// Take.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a specified number of contiguous elements from the start of an observable sequence. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter count: The number of elements to return. + - returns: An observable sequence that contains the specified number of elements from the start of the input sequence. + */ + public func take(_ count: Int) + -> Observable { + if count == 0 { + return Observable.empty() + } + else { + return TakeCount(source: self.asObservable(), count: count) + } + } +} + +extension ObservableType { + /** + Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter duration: Duration for taking elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + public func take(for duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + TakeTime(source: self.asObservable(), duration: duration, scheduler: scheduler) + } + + /** + Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter duration: Duration for taking elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + @available(*, deprecated, renamed: "take(for:scheduler:)") + public func take(_ duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + take(for: duration, scheduler: scheduler) + } +} + +// count version + +final private class TakeCountSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = TakeCount + + private let parent: Parent + + private var remaining: Int + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.remaining = parent.count + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + + if self.remaining > 0 { + self.remaining -= 1 + + self.forwardOn(.next(value)) + + if self.remaining == 0 { + self.forwardOn(.completed) + self.dispose() + } + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + +} + +final private class TakeCount: Producer { + private let source: Observable + fileprivate let count: Int + + init(source: Observable, count: Int) { + if count < 0 { + rxFatalError("count can't be negative") + } + self.source = source + self.count = count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} + +// time version + +final private class TakeTimeSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType where Observer.Element == Element { + typealias Parent = TakeTime + + private let parent: Parent + + let lock = RecursiveLock() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let value): + self.forwardOn(.next(value)) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + func tick() { + self.lock.performLocked { + self.forwardOn(.completed) + self.dispose() + } + } + + func run() -> Disposable { + let disposeTimer = self.parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { _ in + self.tick() + return Disposables.create() + } + + let disposeSubscription = self.parent.source.subscribe(self) + + return Disposables.create(disposeTimer, disposeSubscription) + } +} + +final private class TakeTime: Producer { + typealias TimeInterval = RxTimeInterval + + fileprivate let source: Observable + fileprivate let duration: TimeInterval + fileprivate let scheduler: SchedulerType + + init(source: Observable, duration: TimeInterval, scheduler: SchedulerType) { + self.source = source + self.scheduler = scheduler + self.duration = duration + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeTimeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/TakeLast.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/TakeLast.swift new file mode 100644 index 000000000..91833872d --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/TakeLast.swift @@ -0,0 +1,78 @@ +// +// TakeLast.swift +// RxSwift +// +// Created by Tomi Koskinen on 25/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a specified number of contiguous elements from the end of an observable sequence. + + This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + + - seealso: [takeLast operator on reactivex.io](http://reactivex.io/documentation/operators/takelast.html) + + - parameter count: Number of elements to take from the end of the source sequence. + - returns: An observable sequence containing the specified number of elements from the end of the source sequence. + */ + public func takeLast(_ count: Int) + -> Observable { + TakeLast(source: self.asObservable(), count: count) + } +} + +final private class TakeLastSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = TakeLast + + private let parent: Parent + + private var elements: Queue + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.elements = Queue(capacity: parent.count + 1) + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + self.elements.enqueue(value) + if self.elements.count > self.parent.count { + _ = self.elements.dequeue() + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + for e in self.elements { + self.forwardOn(.next(e)) + } + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class TakeLast: Producer { + private let source: Observable + fileprivate let count: Int + + init(source: Observable, count: Int) { + if count < 0 { + rxFatalError("count can't be negative") + } + self.source = source + self.count = count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeLastSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/TakeWithPredicate.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/TakeWithPredicate.swift new file mode 100644 index 000000000..6c28d19ba --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/TakeWithPredicate.swift @@ -0,0 +1,285 @@ +// +// TakeWithPredicate.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns the elements from the source observable sequence until the other observable sequence produces an element. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter other: Observable sequence that terminates propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + public func take(until other: Source) + -> Observable { + TakeUntil(source: self.asObservable(), other: other.asObservable()) + } + + /** + Returns elements from an observable sequence until the specified condition is true. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter predicate: A function to test each element for a condition. + - parameter behavior: Whether or not to include the last element matching the predicate. Defaults to `exclusive`. + + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test passes. + */ + public func take(until predicate: @escaping (Element) throws -> Bool, + behavior: TakeBehavior = .exclusive) + -> Observable { + TakeUntilPredicate(source: self.asObservable(), + behavior: behavior, + predicate: predicate) + } + + /** + Returns elements from an observable sequence as long as a specified condition is true. + + - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. + */ + public func take(while predicate: @escaping (Element) throws -> Bool, + behavior: TakeBehavior = .exclusive) + -> Observable { + take(until: { try !predicate($0) }, behavior: behavior) + } + + /** + Returns the elements from the source observable sequence until the other observable sequence produces an element. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter other: Observable sequence that terminates propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + @available(*, deprecated, renamed: "take(until:)") + public func takeUntil(_ other: Source) + -> Observable { + take(until: other) + } + + /** + Returns elements from an observable sequence until the specified condition is true. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter behavior: Whether or not to include the last element matching the predicate. + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test passes. + */ + @available(*, deprecated, renamed: "take(until:behavior:)") + public func takeUntil(_ behavior: TakeBehavior, + predicate: @escaping (Element) throws -> Bool) + -> Observable { + take(until: predicate, behavior: behavior) + } + + /** + Returns elements from an observable sequence as long as a specified condition is true. + + - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. + */ + @available(*, deprecated, renamed: "take(while:)") + public func takeWhile(_ predicate: @escaping (Element) throws -> Bool) + -> Observable { + take(until: { try !predicate($0) }, behavior: .exclusive) + } +} + +/// Behaviors for the take operator family. +public enum TakeBehavior { + /// Include the last element matching the predicate. + case inclusive + + /// Exclude the last element matching the predicate. + case exclusive +} + +// MARK: - TakeUntil Observable +final private class TakeUntilSinkOther + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = TakeUntilSink + typealias Element = Other + + private let parent: Parent + + var lock: RecursiveLock { + self.parent.lock + } + + fileprivate let subscription = SingleAssignmentDisposable() + + init(parent: Parent) { + self.parent = parent +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + self.parent.forwardOn(.completed) + self.parent.dispose() + case .error(let e): + self.parent.forwardOn(.error(e)) + self.parent.dispose() + case .completed: + self.subscription.dispose() + } + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} + +final private class TakeUntilSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias Parent = TakeUntil + + private let parent: Parent + + let lock = RecursiveLock() + + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + func run() -> Disposable { + let otherObserver = TakeUntilSinkOther(parent: self) + let otherSubscription = self.parent.other.subscribe(otherObserver) + otherObserver.subscription.setDisposable(otherSubscription) + let sourceSubscription = self.parent.source.subscribe(self) + + return Disposables.create(sourceSubscription, otherObserver.subscription) + } +} + +final private class TakeUntil: Producer { + + fileprivate let source: Observable + fileprivate let other: Observable + + init(source: Observable, other: Observable) { + self.source = source + self.other = other + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeUntilSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +// MARK: - TakeUntil Predicate +final private class TakeUntilPredicateSink + : Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = TakeUntilPredicate + + private let parent: Parent + private var running = true + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if !self.running { + return + } + + do { + self.running = try !self.parent.predicate(value) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + return + } + + if self.running { + self.forwardOn(.next(value)) + } else { + if self.parent.behavior == .inclusive { + self.forwardOn(.next(value)) + } + + self.forwardOn(.completed) + self.dispose() + } + case .error, .completed: + self.forwardOn(event) + self.dispose() + } + } + +} + +final private class TakeUntilPredicate: Producer { + typealias Predicate = (Element) throws -> Bool + + private let source: Observable + fileprivate let predicate: Predicate + fileprivate let behavior: TakeBehavior + + init(source: Observable, + behavior: TakeBehavior, + predicate: @escaping Predicate) { + self.source = source + self.behavior = behavior + self.predicate = predicate + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeUntilPredicateSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Throttle.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Throttle.swift new file mode 100644 index 000000000..86152a837 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Throttle.swift @@ -0,0 +1,160 @@ +// +// Throttle.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension ObservableType { + + /** + Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration. + + This operator makes sure that no two elements are emitted in less then dueTime. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted. + - parameter scheduler: Scheduler to run the throttle timers on. + - returns: The throttled sequence. + */ + public func throttle(_ dueTime: RxTimeInterval, latest: Bool = true, scheduler: SchedulerType) + -> Observable { + Throttle(source: self.asObservable(), dueTime: dueTime, latest: latest, scheduler: scheduler) + } +} + +final private class ThrottleSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias ParentType = Throttle + + private let parent: ParentType + + let lock = RecursiveLock() + + // state + private var lastUnsentElement: Element? + private var lastSentTime: Date? + private var completed: Bool = false + + let cancellable = SerialDisposable() + + init(parent: ParentType, observer: Observer, cancel: Cancelable) { + self.parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = self.parent.source.subscribe(self) + + return Disposables.create(subscription, cancellable) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let element): + let now = self.parent.scheduler.now + + let reducedScheduledTime: RxTimeInterval + + if let lastSendingTime = self.lastSentTime { + reducedScheduledTime = self.parent.dueTime.reduceWithSpanBetween(earlierDate: lastSendingTime, laterDate: now) + } + else { + reducedScheduledTime = .nanoseconds(0) + } + + if reducedScheduledTime.isNow { + self.sendNow(element: element) + return + } + + if !self.parent.latest { + return + } + + let isThereAlreadyInFlightRequest = self.lastUnsentElement != nil + + self.lastUnsentElement = element + + if isThereAlreadyInFlightRequest { + return + } + + let scheduler = self.parent.scheduler + + let d = SingleAssignmentDisposable() + self.cancellable.disposable = d + + d.setDisposable(scheduler.scheduleRelative(0, dueTime: reducedScheduledTime, action: self.propagate)) + case .error: + self.lastUnsentElement = nil + self.forwardOn(event) + self.dispose() + case .completed: + if self.lastUnsentElement != nil { + self.completed = true + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + } + + private func sendNow(element: Element) { + self.lastUnsentElement = nil + self.forwardOn(.next(element)) + // in case element processing takes a while, this should give some more room + self.lastSentTime = self.parent.scheduler.now + } + + func propagate(_: Int) -> Disposable { + self.lock.performLocked { + if let lastUnsentElement = self.lastUnsentElement { + self.sendNow(element: lastUnsentElement) + } + + if self.completed { + self.forwardOn(.completed) + self.dispose() + } + } + + return Disposables.create() + } +} + +final private class Throttle: Producer { + fileprivate let source: Observable + fileprivate let dueTime: RxTimeInterval + fileprivate let latest: Bool + fileprivate let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, latest: Bool, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.latest = latest + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ThrottleSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Timeout.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Timeout.swift new file mode 100644 index 000000000..efcc7917d --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Timeout.swift @@ -0,0 +1,151 @@ +// +// Timeout.swift +// RxSwift +// +// Created by Tomi Koskinen on 13/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer. + + - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) + + - parameter dueTime: Maximum duration between values before a timeout occurs. + - parameter scheduler: Scheduler to run the timeout timer on. + - returns: An observable sequence with a `RxError.timeout` in case of a timeout. + */ + public func timeout(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Timeout(source: self.asObservable(), dueTime: dueTime, other: Observable.error(RxError.timeout), scheduler: scheduler) + } + + /** + Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on. + + - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) + + - parameter dueTime: Maximum duration between values before a timeout occurs. + - parameter other: Sequence to return in case of a timeout. + - parameter scheduler: Scheduler to run the timeout timer on. + - returns: The source sequence switching to the other sequence in case of a timeout. + */ + public func timeout(_ dueTime: RxTimeInterval, other: Source, scheduler: SchedulerType) + -> Observable where Element == Source.Element { + return Timeout(source: self.asObservable(), dueTime: dueTime, other: other.asObservable(), scheduler: scheduler) + } +} + +final private class TimeoutSink: Sink, LockOwnerType, ObserverType { + typealias Element = Observer.Element + typealias Parent = Timeout + + private let parent: Parent + + let lock = RecursiveLock() + + private let timerD = SerialDisposable() + private let subscription = SerialDisposable() + + private var id = 0 + private var switched = false + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let original = SingleAssignmentDisposable() + self.subscription.disposable = original + + self.createTimeoutTimer() + + original.setDisposable(self.parent.source.subscribe(self)) + + return Disposables.create(subscription, timerD) + } + + func on(_ event: Event) { + switch event { + case .next: + var onNextWins = false + + self.lock.performLocked { + onNextWins = !self.switched + if onNextWins { + self.id = self.id &+ 1 + } + } + + if onNextWins { + self.forwardOn(event) + self.createTimeoutTimer() + } + case .error, .completed: + var onEventWins = false + + self.lock.performLocked { + onEventWins = !self.switched + if onEventWins { + self.id = self.id &+ 1 + } + } + + if onEventWins { + self.forwardOn(event) + self.dispose() + } + } + } + + private func createTimeoutTimer() { + if self.timerD.isDisposed { + return + } + + let nextTimer = SingleAssignmentDisposable() + self.timerD.disposable = nextTimer + + let disposeSchedule = self.parent.scheduler.scheduleRelative(self.id, dueTime: self.parent.dueTime) { state in + + var timerWins = false + + self.lock.performLocked { + self.switched = (state == self.id) + timerWins = self.switched + } + + if timerWins { + self.subscription.disposable = self.parent.other.subscribe(self.forwarder()) + } + + return Disposables.create() + } + + nextTimer.setDisposable(disposeSchedule) + } +} + + +final private class Timeout: Producer { + fileprivate let source: Observable + fileprivate let dueTime: RxTimeInterval + fileprivate let other: Observable + fileprivate let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, other: Observable, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.other = other + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TimeoutSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Timer.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Timer.swift new file mode 100644 index 000000000..30bbdf67d --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Timer.swift @@ -0,0 +1,117 @@ +// +// Timer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where Element: RxAbstractInteger { + /** + Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. + + - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html) + + - parameter period: Period for producing the values in the resulting sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence that produces a value after each period. + */ + public static func interval(_ period: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Timer( + dueTime: period, + period: period, + scheduler: scheduler + ) + } +} + +extension ObservableType where Element: RxAbstractInteger { + /** + Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. + + - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) + + - parameter dueTime: Relative time at which to produce the first value. + - parameter period: Period to produce subsequent values. + - parameter scheduler: Scheduler to run timers on. + - returns: An observable sequence that produces a value after due time has elapsed and then each period. + */ + public static func timer(_ dueTime: RxTimeInterval, period: RxTimeInterval? = nil, scheduler: SchedulerType) + -> Observable { + return Timer( + dueTime: dueTime, + period: period, + scheduler: scheduler + ) + } +} + +import Foundation + +final private class TimerSink : Sink where Observer.Element : RxAbstractInteger { + typealias Parent = Timer + + private let parent: Parent + private let lock = RecursiveLock() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.schedulePeriodic(0 as Observer.Element, startAfter: self.parent.dueTime, period: self.parent.period!) { state in + self.lock.performLocked { + self.forwardOn(.next(state)) + return state &+ 1 + } + } + } +} + +final private class TimerOneOffSink: Sink where Observer.Element: RxAbstractInteger { + typealias Parent = Timer + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRelative(self, dueTime: self.parent.dueTime) { [unowned self] _ -> Disposable in + self.forwardOn(.next(0)) + self.forwardOn(.completed) + self.dispose() + + return Disposables.create() + } + } +} + +final private class Timer: Producer { + fileprivate let scheduler: SchedulerType + fileprivate let dueTime: RxTimeInterval + fileprivate let period: RxTimeInterval? + + init(dueTime: RxTimeInterval, period: RxTimeInterval?, scheduler: SchedulerType) { + self.scheduler = scheduler + self.dueTime = dueTime + self.period = period + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + if self.period != nil { + let sink = TimerSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + else { + let sink = TimerOneOffSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/ToArray.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/ToArray.swift new file mode 100644 index 000000000..76c7370aa --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/ToArray.swift @@ -0,0 +1,64 @@ +// +// ToArray.swift +// RxSwift +// +// Created by Junior B. on 20/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Converts an Observable into a Single that emits the whole sequence as a single array and then terminates. + + For aggregation behavior see `reduce`. + + - seealso: [toArray operator on reactivex.io](http://reactivex.io/documentation/operators/to.html) + + - returns: A Single sequence containing all the emitted elements as array. + */ + public func toArray() + -> Single<[Element]> { + PrimitiveSequence(raw: ToArray(source: self.asObservable())) + } +} + +final private class ToArraySink: Sink, ObserverType where Observer.Element == [SourceType] { + typealias Parent = ToArray + + let parent: Parent + var list = [SourceType]() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + self.list.append(value) + case .error(let e): + self.forwardOn(.error(e)) + self.dispose() + case .completed: + self.forwardOn(.next(self.list)) + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class ToArray: Producer<[SourceType]> { + let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == [SourceType] { + let sink = ToArraySink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Using.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Using.swift new file mode 100644 index 000000000..ca48d2fb8 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Using.swift @@ -0,0 +1,90 @@ +// +// Using.swift +// RxSwift +// +// Created by Yury Korolev on 10/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. + + - seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html) + + - parameter resourceFactory: Factory function to obtain a resource object. + - parameter observableFactory: Factory function to obtain an observable sequence that depends on the obtained resource. + - returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object. + */ + public static func using(_ resourceFactory: @escaping () throws -> Resource, observableFactory: @escaping (Resource) throws -> Observable) -> Observable { + Using(resourceFactory: resourceFactory, observableFactory: observableFactory) + } +} + +final private class UsingSink: Sink, ObserverType { + typealias SourceType = Observer.Element + typealias Parent = Using + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + var disposable = Disposables.create() + + do { + let resource = try self.parent.resourceFactory() + disposable = resource + let source = try self.parent.observableFactory(resource) + + return Disposables.create( + source.subscribe(self), + disposable + ) + } catch let error { + return Disposables.create( + Observable.error(error).subscribe(self), + disposable + ) + } + } + + func on(_ event: Event) { + switch event { + case let .next(value): + self.forwardOn(.next(value)) + case let .error(error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class Using: Producer { + + typealias Element = SourceType + + typealias ResourceFactory = () throws -> ResourceType + typealias ObservableFactory = (ResourceType) throws -> Observable + + fileprivate let resourceFactory: ResourceFactory + fileprivate let observableFactory: ObservableFactory + + + init(resourceFactory: @escaping ResourceFactory, observableFactory: @escaping ObservableFactory) { + self.resourceFactory = resourceFactory + self.observableFactory = observableFactory + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = UsingSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Window.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Window.swift new file mode 100644 index 000000000..b2a37a5c4 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Window.swift @@ -0,0 +1,168 @@ +// +// Window.swift +// RxSwift +// +// Created by Junior B. on 29/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a window that is completed when either it’s full or a given amount of time has elapsed. + + - seealso: [window operator on reactivex.io](http://reactivex.io/documentation/operators/window.html) + + - parameter timeSpan: Maximum time length of a window. + - parameter count: Maximum element count of a window. + - parameter scheduler: Scheduler to run windowing timers on. + - returns: An observable sequence of windows (instances of `Observable`). + */ + public func window(timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) + -> Observable> { + return WindowTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) + } +} + +final private class WindowTimeCountSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType where Observer.Element == Observable { + typealias Parent = WindowTimeCount + + private let parent: Parent + + let lock = RecursiveLock() + + private var subject = PublishSubject() + private var count = 0 + private var windowId = 0 + + private let timerD = SerialDisposable() + private let refCountDisposable: RefCountDisposable + private let groupDisposable = CompositeDisposable() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + + _ = self.groupDisposable.insert(self.timerD) + + self.refCountDisposable = RefCountDisposable(disposable: self.groupDisposable) + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + + self.forwardOn(.next(AddRef(source: self.subject, refCount: self.refCountDisposable).asObservable())) + self.createTimer(self.windowId) + + _ = self.groupDisposable.insert(self.parent.source.subscribe(self)) + return self.refCountDisposable + } + + func startNewWindowAndCompleteCurrentOne() { + self.subject.on(.completed) + self.subject = PublishSubject() + + self.forwardOn(.next(AddRef(source: self.subject, refCount: self.refCountDisposable).asObservable())) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + var newWindow = false + var newId = 0 + + switch event { + case .next(let element): + self.subject.on(.next(element)) + + do { + _ = try incrementChecked(&self.count) + } catch let e { + self.subject.on(.error(e as Swift.Error)) + self.dispose() + } + + if self.count == self.parent.count { + newWindow = true + self.count = 0 + self.windowId += 1 + newId = self.windowId + self.startNewWindowAndCompleteCurrentOne() + } + + case .error(let error): + self.subject.on(.error(error)) + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.subject.on(.completed) + self.forwardOn(.completed) + self.dispose() + } + + if newWindow { + self.createTimer(newId) + } + } + + func createTimer(_ windowId: Int) { + if self.timerD.isDisposed { + return + } + + if self.windowId != windowId { + return + } + + let nextTimer = SingleAssignmentDisposable() + + self.timerD.disposable = nextTimer + + let scheduledRelative = self.parent.scheduler.scheduleRelative(windowId, dueTime: self.parent.timeSpan) { previousWindowId in + + var newId = 0 + + self.lock.performLocked { + if previousWindowId != self.windowId { + return + } + + self.count = 0 + self.windowId = self.windowId &+ 1 + newId = self.windowId + self.startNewWindowAndCompleteCurrentOne() + } + + self.createTimer(newId) + + return Disposables.create() + } + + nextTimer.setDisposable(scheduledRelative) + } +} + +final private class WindowTimeCount: Producer> { + fileprivate let timeSpan: RxTimeInterval + fileprivate let count: Int + fileprivate let scheduler: SchedulerType + fileprivate let source: Observable + + init(source: Observable, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { + self.source = source + self.timeSpan = timeSpan + self.count = count + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Observable { + let sink = WindowTimeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/WithLatestFrom.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/WithLatestFrom.swift new file mode 100644 index 000000000..d2868121a --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/WithLatestFrom.swift @@ -0,0 +1,151 @@ +// +// WithLatestFrom.swift +// RxSwift +// +// Created by Yury Korolev on 10/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + - note: Elements emitted by self before the second source has emitted any values will be omitted. + + - parameter second: Second observable source. + - parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: Source, resultSelector: @escaping (Element, Source.Element) throws -> ResultType) -> Observable { + WithLatestFrom(first: self.asObservable(), second: second.asObservable(), resultSelector: resultSelector) + } + + /** + Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emits an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + - note: Elements emitted by self before the second source has emitted any values will be omitted. + + - parameter second: Second observable source. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: Source) -> Observable { + WithLatestFrom(first: self.asObservable(), second: second.asObservable(), resultSelector: { $1 }) + } +} + +final private class WithLatestFromSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias ResultType = Observer.Element + typealias Parent = WithLatestFrom + typealias Element = FirstType + + private let parent: Parent + + fileprivate var lock = RecursiveLock() + fileprivate var latest: SecondType? + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let sndSubscription = SingleAssignmentDisposable() + let sndO = WithLatestFromSecond(parent: self, disposable: sndSubscription) + + sndSubscription.setDisposable(self.parent.second.subscribe(sndO)) + let fstSubscription = self.parent.first.subscribe(self) + + return Disposables.create(fstSubscription, sndSubscription) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case let .next(value): + guard let latest = self.latest else { return } + do { + let res = try self.parent.resultSelector(value, latest) + + self.forwardOn(.next(res)) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .completed: + self.forwardOn(.completed) + self.dispose() + case let .error(error): + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class WithLatestFromSecond + : ObserverType + , LockOwnerType + , SynchronizedOnType { + + typealias ResultType = Observer.Element + typealias Parent = WithLatestFromSink + typealias Element = SecondType + + private let parent: Parent + private let disposable: Disposable + + var lock: RecursiveLock { + self.parent.lock + } + + init(parent: Parent, disposable: Disposable) { + self.parent = parent + self.disposable = disposable + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case let .next(value): + self.parent.latest = value + case .completed: + self.disposable.dispose() + case let .error(error): + self.parent.forwardOn(.error(error)) + self.parent.dispose() + } + } +} + +final private class WithLatestFrom: Producer { + typealias ResultSelector = (FirstType, SecondType) throws -> ResultType + + fileprivate let first: Observable + fileprivate let second: Observable + fileprivate let resultSelector: ResultSelector + + init(first: Observable, second: Observable, resultSelector: @escaping ResultSelector) { + self.first = first + self.second = second + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { + let sink = WithLatestFromSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/WithUnretained.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/WithUnretained.swift new file mode 100644 index 000000000..076f6de84 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/WithUnretained.swift @@ -0,0 +1,58 @@ +// +// WithUnretained.swift +// RxSwift +// +// Created by Vincent Pradeilles on 01/01/2021. +// Copyright © 2020 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. + + In the case the provided object cannot be retained successfully, the sequence will complete. + + - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. + + - parameter obj: The object to provide an unretained reference on. + - parameter resultSelector: A function to combine the unretained referenced on `obj` and the value of the observable sequence. + - returns: An observable sequence that contains the result of `resultSelector` being called with an unretained reference on `obj` and the values of the original sequence. + */ + public func withUnretained( + _ obj: Object, + resultSelector: @escaping (Object, Element) -> Out + ) -> Observable { + map { [weak obj] element -> Out in + guard let obj = obj else { throw UnretainedError.failedRetaining } + + return resultSelector(obj, element) + } + .catch{ error -> Observable in + guard let unretainedError = error as? UnretainedError, + unretainedError == .failedRetaining else { + return .error(error) + } + + return .empty() + } + } + + + /** + Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. + + In the case the provided object cannot be retained successfully, the sequence will complete. + + - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. + + - parameter obj: The object to provide an unretained reference on. + - returns: An observable sequence of tuples that contains both an unretained reference on `obj` and the values of the original sequence. + */ + public func withUnretained(_ obj: Object) -> Observable<(Object, Element)> { + return withUnretained(obj) { ($0, $1) } + } +} + +private enum UnretainedError: Swift.Error { + case failedRetaining +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Zip+Collection.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Zip+Collection.swift new file mode 100644 index 000000000..2d7f8877c --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Zip+Collection.swift @@ -0,0 +1,168 @@ +// +// Zip+Collection.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip(_ collection: Collection, resultSelector: @escaping ([Collection.Element.Element]) throws -> Element) -> Observable + where Collection.Element: ObservableType { + ZipCollectionType(sources: collection, resultSelector: resultSelector) + } + + /** + Merges the specified observable sequences into one observable sequence whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip(_ collection: Collection) -> Observable<[Element]> + where Collection.Element: ObservableType, Collection.Element.Element == Element { + ZipCollectionType(sources: collection, resultSelector: { $0 }) + } + +} + +final private class ZipCollectionTypeSink + : Sink where Collection.Element: ObservableConvertibleType { + typealias Result = Observer.Element + typealias Parent = ZipCollectionType + typealias SourceElement = Collection.Element.Element + + private let parent: Parent + + private let lock = RecursiveLock() + + // state + private var numberOfValues = 0 + private var values: [Queue] + private var isDone: [Bool] + private var numberOfDone = 0 + private var subscriptions: [SingleAssignmentDisposable] + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.values = [Queue](repeating: Queue(capacity: 4), count: parent.count) + self.isDone = [Bool](repeating: false, count: parent.count) + self.subscriptions = [SingleAssignmentDisposable]() + self.subscriptions.reserveCapacity(parent.count) + + for _ in 0 ..< parent.count { + self.subscriptions.append(SingleAssignmentDisposable()) + } + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event, atIndex: Int) { + self.lock.lock(); defer { self.lock.unlock() } + switch event { + case .next(let element): + self.values[atIndex].enqueue(element) + + if self.values[atIndex].count == 1 { + self.numberOfValues += 1 + } + + if self.numberOfValues < self.parent.count { + if self.numberOfDone == self.parent.count - 1 { + self.forwardOn(.completed) + self.dispose() + } + return + } + + do { + var arguments = [SourceElement]() + arguments.reserveCapacity(self.parent.count) + + // recalculate number of values + self.numberOfValues = 0 + + for i in 0 ..< self.values.count { + arguments.append(self.values[i].dequeue()!) + if !self.values[i].isEmpty { + self.numberOfValues += 1 + } + } + + let result = try self.parent.resultSelector(arguments) + self.forwardOn(.next(result)) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + if self.isDone[atIndex] { + return + } + + self.isDone[atIndex] = true + self.numberOfDone += 1 + + if self.numberOfDone == self.parent.count { + self.forwardOn(.completed) + self.dispose() + } + else { + self.subscriptions[atIndex].dispose() + } + } + } + + func run() -> Disposable { + var j = 0 + for i in self.parent.sources { + let index = j + let source = i.asObservable() + + let disposable = source.subscribe(AnyObserver { event in + self.on(event, atIndex: index) + }) + self.subscriptions[j].setDisposable(disposable) + j += 1 + } + + if self.parent.sources.isEmpty { + self.forwardOn(.completed) + } + + return Disposables.create(subscriptions) + } +} + +final private class ZipCollectionType: Producer where Collection.Element: ObservableConvertibleType { + typealias ResultSelector = ([Collection.Element.Element]) throws -> Result + + let sources: Collection + let resultSelector: ResultSelector + let count: Int + + init(sources: Collection, resultSelector: @escaping ResultSelector) { + self.sources = sources + self.resultSelector = resultSelector + self.count = self.sources.count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipCollectionTypeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Zip+arity.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Zip+arity.swift new file mode 100644 index 000000000..b6d876d1d --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Zip+arity.swift @@ -0,0 +1,934 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// Zip+arity.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + + +// 2 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.Element, O2.Element) throws -> Element) + -> Observable { + return Zip2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2) + -> Observable<(O1.Element, O2.Element)> { + return Zip2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: { ($0, $1) } + ) + } +} + +final class ZipSink2_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip2 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 2, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + + return Disposables.create([ + subscription1, + subscription2 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!) + } +} + +final class Zip2 : Producer { + typealias ResultSelector = (E1, E2) throws -> Result + + let source1: Observable + let source2: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink2_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 3 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.Element, O2.Element, O3.Element) throws -> Element) + -> Observable { + return Zip3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3) + -> Observable<(O1.Element, O2.Element, O3.Element)> { + return Zip3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: { ($0, $1, $2) } + ) + } +} + +final class ZipSink3_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip3 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 3, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!) + } +} + +final class Zip3 : Producer { + typealias ResultSelector = (E1, E2, E3) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink3_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 4 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element) throws -> Element) + -> Observable { + return Zip4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element)> { + return Zip4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: { ($0, $1, $2, $3) } + ) + } +} + +final class ZipSink4_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip4 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 4, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!) + } +} + +final class Zip4 : Producer { + typealias ResultSelector = (E1, E2, E3, E4) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink4_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 5 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element) throws -> Element) + -> Observable { + return Zip5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element)> { + return Zip5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4) } + ) + } +} + +final class ZipSink5_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip5 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + var values5: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 5, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + case 4: return !self.values5.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self.lock, parent: self, index: 4, setNextValue: { self.values5.enqueue($0) }, this: subscription5) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!, self.values5.dequeue()!) + } +} + +final class Zip5 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink5_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 6 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element) throws -> Element) + -> Observable { + return Zip6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element)> { + return Zip6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5) } + ) + } +} + +final class ZipSink6_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip6 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + var values5: Queue = Queue(capacity: 2) + var values6: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 6, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + case 4: return !self.values5.isEmpty + case 5: return !self.values6.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self.lock, parent: self, index: 4, setNextValue: { self.values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: self.lock, parent: self, index: 5, setNextValue: { self.values6.enqueue($0) }, this: subscription6) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!, self.values5.dequeue()!, self.values6.dequeue()!) + } +} + +final class Zip6 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink6_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 7 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element) throws -> Element) + -> Observable { + return Zip7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element)> { + return Zip7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6) } + ) + } +} + +final class ZipSink7_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip7 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + var values5: Queue = Queue(capacity: 2) + var values6: Queue = Queue(capacity: 2) + var values7: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 7, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + case 4: return !self.values5.isEmpty + case 5: return !self.values6.isEmpty + case 6: return !self.values7.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self.lock, parent: self, index: 4, setNextValue: { self.values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: self.lock, parent: self, index: 5, setNextValue: { self.values6.enqueue($0) }, this: subscription6) + let observer7 = ZipObserver(lock: self.lock, parent: self, index: 6, setNextValue: { self.values7.enqueue($0) }, this: subscription7) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + subscription7.setDisposable(self.parent.source7.subscribe(observer7)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!, self.values5.dequeue()!, self.values6.dequeue()!, self.values7.dequeue()!) + } +} + +final class Zip7 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink7_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 8 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element) throws -> Element) + -> Observable { + return Zip8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element)> { + return Zip8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6, $7) } + ) + } +} + +final class ZipSink8_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip8 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + var values5: Queue = Queue(capacity: 2) + var values6: Queue = Queue(capacity: 2) + var values7: Queue = Queue(capacity: 2) + var values8: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 8, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + case 4: return !self.values5.isEmpty + case 5: return !self.values6.isEmpty + case 6: return !self.values7.isEmpty + case 7: return !self.values8.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + let subscription8 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self.lock, parent: self, index: 4, setNextValue: { self.values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: self.lock, parent: self, index: 5, setNextValue: { self.values6.enqueue($0) }, this: subscription6) + let observer7 = ZipObserver(lock: self.lock, parent: self, index: 6, setNextValue: { self.values7.enqueue($0) }, this: subscription7) + let observer8 = ZipObserver(lock: self.lock, parent: self, index: 7, setNextValue: { self.values8.enqueue($0) }, this: subscription8) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + subscription7.setDisposable(self.parent.source7.subscribe(observer7)) + subscription8.setDisposable(self.parent.source8.subscribe(observer8)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7, + subscription8 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!, self.values5.dequeue()!, self.values6.dequeue()!, self.values7.dequeue()!, self.values8.dequeue()!) + } +} + +final class Zip8 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + let source8: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, source8: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + self.source8 = source8 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink8_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Zip+arity.tt b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Zip+arity.tt new file mode 100644 index 000000000..447073c3a --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Zip+arity.tt @@ -0,0 +1,120 @@ +// +// Zip+arity.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +<% for i in 2 ... 8 { %> + +// <%= i %> + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip<<%= (Array(1...i).map { "O\($0): ObservableType" }).joined(separator: ", ") %>> + (<%= (Array(1...i).map { "_ source\($0): O\($0)" }).joined(separator: ", ") %>, resultSelector: @escaping (<%= (Array(1...i).map { "O\($0).Element" }).joined(separator: ", ") %>) throws -> Element) + -> Observable { + return Zip<%= i %>( + <%= (Array(1...i).map { "source\($0): source\($0).asObservable()" }).joined(separator: ", ") %>, + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip<<%= (Array(1...i).map { "O\($0): ObservableType" }).joined(separator: ", ") %>> + (<%= (Array(1...i).map { "_ source\($0): O\($0)" }).joined(separator: ", ") %>) + -> Observable<(<%= (Array(1...i).map { "O\($0).Element" }).joined(separator: ", ") %>)> { + return Zip<%= i %>( + <%= (Array(1...i).map { "source\($0): source\($0).asObservable()" }).joined(separator: ", ") %>, + resultSelector: { (<%= (Array(0..) } + ) + } +} + +final class ZipSink<%= i %>_<<%= (Array(1...i).map { "E\($0)" }).joined(separator: ", ") %>, Observer: ObserverType> : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip<%= i %><<%= (Array(1...i).map { "E\($0)" }).joined(separator: ", ") %>, Result> + + let parent: Parent + +<%= (Array(1...i).map { +" var values\($0): Queue = Queue(capacity: 2)" +}).joined(separator: "\n") %> + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: <%= i %>, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { +<%= (Array(0.. + default: + rxFatalError("Unhandled case \(index)") + } + } + + func run() -> Disposable { +<%= (Array(1...i).map { +" let subscription\($0) = SingleAssignmentDisposable()" +}).joined(separator: "\n") %> + +<%= (Array(1...i).map { +" let observer\($0) = ZipObserver(lock: self.lock, parent: self, index: \($0 - 1), setNextValue: { self.values\($0).enqueue($0) }, this: subscription\($0))" +}).joined(separator: "\n") %> + +<%= (Array(1...i).map { +" subscription\($0).setDisposable(self.parent.source\($0).subscribe(observer\($0)))" }).joined(separator: "\n") +%> + + return Disposables.create([ +<%= (Array(1...i).map { " subscription\($0)" }).joined(separator: ",\n") %> + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(<%= (Array(1...i).map { "self.values\($0).dequeue()!" }).joined(separator: ", ") %>) + } +} + +final class Zip<%= i %><<%= (Array(1...i).map { "E\($0)" }).joined(separator: ", ") %>, Result> : Producer { + typealias ResultSelector = (<%= (Array(1...i).map { "E\($0)" }).joined(separator: ", ") %>) throws -> Result + +<%= (Array(1...i).map { " let source\($0): Observable" }).joined(separator: "\n") %> + + let resultSelector: ResultSelector + + init(<%= (Array(1...i).map { "source\($0): Observable" }).joined(separator: ", ") %>, resultSelector: @escaping ResultSelector) { +<%= (Array(1...i).map { +" self.source\($0) = source\($0)" }).joined(separator: "\n") +%> + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink<%= i %>_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +<% } %> diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Zip.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Zip.swift new file mode 100644 index 000000000..328a40ef7 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observables/Zip.swift @@ -0,0 +1,135 @@ +// +// Zip.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol ZipSinkProtocol: AnyObject { + func next(_ index: Int) + func fail(_ error: Swift.Error) + func done(_ index: Int) +} + +class ZipSink : Sink, ZipSinkProtocol { + typealias Element = Observer.Element + + let arity: Int + + let lock = RecursiveLock() + + // state + private var isDone: [Bool] + + init(arity: Int, observer: Observer, cancel: Cancelable) { + self.isDone = [Bool](repeating: false, count: arity) + self.arity = arity + + super.init(observer: observer, cancel: cancel) + } + + func getResult() throws -> Element { + rxAbstractMethod() + } + + func hasElements(_ index: Int) -> Bool { + rxAbstractMethod() + } + + func next(_ index: Int) { + var hasValueAll = true + + for i in 0 ..< self.arity { + if !self.hasElements(i) { + hasValueAll = false + break + } + } + + if hasValueAll { + do { + let result = try self.getResult() + self.forwardOn(.next(result)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + } + + func fail(_ error: Swift.Error) { + self.forwardOn(.error(error)) + self.dispose() + } + + func done(_ index: Int) { + self.isDone[index] = true + + var allDone = true + + for done in self.isDone where !done { + allDone = false + break + } + + if allDone { + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class ZipObserver + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias ValueSetter = (Element) -> Void + + private var parent: ZipSinkProtocol? + + let lock: RecursiveLock + + // state + private let index: Int + private let this: Disposable + private let setNextValue: ValueSetter + + init(lock: RecursiveLock, parent: ZipSinkProtocol, index: Int, setNextValue: @escaping ValueSetter, this: Disposable) { + self.lock = lock + self.parent = parent + self.index = index + self.this = this + self.setNextValue = setNextValue + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + if self.parent != nil { + switch event { + case .next: + break + case .error: + self.this.dispose() + case .completed: + self.this.dispose() + } + } + + if let parent = self.parent { + switch event { + case .next(let value): + self.setNextValue(value) + parent.next(self.index) + case .error(let error): + parent.fail(error) + case .completed: + parent.done(self.index) + } + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/ObserverType.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/ObserverType.swift new file mode 100644 index 000000000..b7a66480e --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/ObserverType.swift @@ -0,0 +1,40 @@ +// +// ObserverType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Supports push-style iteration over an observable sequence. +public protocol ObserverType { + /// The type of elements in sequence that observer can observe. + associatedtype Element + + /// Notify observer about sequence event. + /// + /// - parameter event: Event that occurred. + func on(_ event: Event) +} + +/// Convenience API extensions to provide alternate next, error, completed events +extension ObserverType { + + /// Convenience method equivalent to `on(.next(element: Element))` + /// + /// - parameter element: Next element to send to observer(s) + public func onNext(_ element: Element) { + self.on(.next(element)) + } + + /// Convenience method equivalent to `on(.completed)` + public func onCompleted() { + self.on(.completed) + } + + /// Convenience method equivalent to `on(.error(Swift.Error))` + /// - parameter error: Swift.Error to send to observer(s) + public func onError(_ error: Swift.Error) { + self.on(.error(error)) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observers/AnonymousObserver.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observers/AnonymousObserver.swift new file mode 100644 index 000000000..cbb42dc82 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observers/AnonymousObserver.swift @@ -0,0 +1,30 @@ +// +// AnonymousObserver.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +final class AnonymousObserver: ObserverBase { + typealias EventHandler = (Event) -> Void + + private let eventHandler : EventHandler + + init(_ eventHandler: @escaping EventHandler) { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + self.eventHandler = eventHandler + } + + override func onCore(_ event: Event) { + self.eventHandler(event) + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observers/ObserverBase.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observers/ObserverBase.swift new file mode 100644 index 000000000..48e09868b --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observers/ObserverBase.swift @@ -0,0 +1,32 @@ +// +// ObserverBase.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class ObserverBase : Disposable, ObserverType { + private let isStopped = AtomicInt(0) + + func on(_ event: Event) { + switch event { + case .next: + if load(self.isStopped) == 0 { + self.onCore(event) + } + case .error, .completed: + if fetchOr(self.isStopped, 1) == 0 { + self.onCore(event) + } + } + } + + func onCore(_ event: Event) { + rxAbstractMethod() + } + + func dispose() { + fetchOr(self.isStopped, 1) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observers/TailRecursiveSink.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observers/TailRecursiveSink.swift new file mode 100644 index 000000000..fd527001d --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Observers/TailRecursiveSink.swift @@ -0,0 +1,151 @@ +// +// TailRecursiveSink.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +enum TailRecursiveSinkCommand { + case moveNext + case dispose +} + +#if DEBUG || TRACE_RESOURCES + public var maxTailRecursiveSinkStackSize = 0 +#endif + +/// This class is usually used with `Generator` version of the operators. +class TailRecursiveSink + : Sink + , InvocableWithValueType where Sequence.Element: ObservableConvertibleType, Sequence.Element.Element == Observer.Element { + typealias Value = TailRecursiveSinkCommand + typealias Element = Observer.Element + typealias SequenceGenerator = (generator: Sequence.Iterator, remaining: IntMax?) + + var generators: [SequenceGenerator] = [] + var disposed = false + var subscription = SerialDisposable() + + // this is thread safe object + var gate = AsyncLock>>() + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func run(_ sources: SequenceGenerator) -> Disposable { + self.generators.append(sources) + + self.schedule(.moveNext) + + return self.subscription + } + + func invoke(_ command: TailRecursiveSinkCommand) { + switch command { + case .dispose: + self.disposeCommand() + case .moveNext: + self.moveNextCommand() + } + } + + // simple implementation for now + func schedule(_ command: TailRecursiveSinkCommand) { + self.gate.invoke(InvocableScheduledItem(invocable: self, state: command)) + } + + func done() { + self.forwardOn(.completed) + self.dispose() + } + + func extract(_ observable: Observable) -> SequenceGenerator? { + rxAbstractMethod() + } + + // should be done on gate locked + + private func moveNextCommand() { + var next: Observable? + + repeat { + guard let (g, left) = self.generators.last else { + break + } + + if self.isDisposed { + return + } + + self.generators.removeLast() + + var e = g + + guard let nextCandidate = e.next()?.asObservable() else { + continue + } + + // `left` is a hint of how many elements are left in generator. + // In case this is the last element, then there is no need to push + // that generator on stack. + // + // This is an optimization used to make sure in tail recursive case + // there is no memory leak in case this operator is used to generate non terminating + // sequence. + + if let knownOriginalLeft = left { + // `- 1` because generator.next() has just been called + if knownOriginalLeft - 1 >= 1 { + self.generators.append((e, knownOriginalLeft - 1)) + } + } + else { + self.generators.append((e, nil)) + } + + let nextGenerator = self.extract(nextCandidate) + + if let nextGenerator = nextGenerator { + self.generators.append(nextGenerator) + #if DEBUG || TRACE_RESOURCES + if maxTailRecursiveSinkStackSize < self.generators.count { + maxTailRecursiveSinkStackSize = self.generators.count + } + #endif + } + else { + next = nextCandidate + } + } while next == nil + + guard let existingNext = next else { + self.done() + return + } + + let disposable = SingleAssignmentDisposable() + self.subscription.disposable = disposable + disposable.setDisposable(self.subscribeToNext(existingNext)) + } + + func subscribeToNext(_ source: Observable) -> Disposable { + rxAbstractMethod() + } + + func disposeCommand() { + self.disposed = true + self.generators.removeAll(keepingCapacity: false) + } + + override func dispose() { + super.dispose() + + self.subscription.dispose() + self.gate.dispose() + + self.schedule(.dispose) + } +} + diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/AtomicInt.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/AtomicInt.swift new file mode 100644 index 000000000..bf19c5be1 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/AtomicInt.swift @@ -0,0 +1,72 @@ +// +// AtomicInt.swift +// Platform +// +// Created by Krunoslav Zaher on 10/28/18. +// Copyright © 2018 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +final class AtomicInt: NSLock { + fileprivate var value: Int32 + public init(_ value: Int32 = 0) { + self.value = value + } +} + +@discardableResult +@inline(__always) +func add(_ this: AtomicInt, _ value: Int32) -> Int32 { + this.lock() + let oldValue = this.value + this.value += value + this.unlock() + return oldValue +} + +@discardableResult +@inline(__always) +func sub(_ this: AtomicInt, _ value: Int32) -> Int32 { + this.lock() + let oldValue = this.value + this.value -= value + this.unlock() + return oldValue +} + +@discardableResult +@inline(__always) +func fetchOr(_ this: AtomicInt, _ mask: Int32) -> Int32 { + this.lock() + let oldValue = this.value + this.value |= mask + this.unlock() + return oldValue +} + +@inline(__always) +func load(_ this: AtomicInt) -> Int32 { + this.lock() + let oldValue = this.value + this.unlock() + return oldValue +} + +@discardableResult +@inline(__always) +func increment(_ this: AtomicInt) -> Int32 { + add(this, 1) +} + +@discardableResult +@inline(__always) +func decrement(_ this: AtomicInt) -> Int32 { + sub(this, 1) +} + +@inline(__always) +func isFlagSet(_ this: AtomicInt, _ mask: Int32) -> Bool { + (load(this) & mask) != 0 +} + diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DataStructures/Bag.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DataStructures/Bag.swift new file mode 100644 index 000000000..9f5f0171f --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DataStructures/Bag.swift @@ -0,0 +1,181 @@ +// +// Bag.swift +// Platform +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Swift + +let arrayDictionaryMaxSize = 30 + +struct BagKey { + /** + Unique identifier for object added to `Bag`. + + It's underlying type is UInt64. If we assume there in an idealized CPU that works at 4GHz, + it would take ~150 years of continuous running time for it to overflow. + */ + fileprivate let rawValue: UInt64 +} + +/** +Data structure that represents a bag of elements typed `T`. + +Single element can be stored multiple times. + +Time and space complexity of insertion and deletion is O(n). + +It is suitable for storing small number of elements. +*/ +struct Bag : CustomDebugStringConvertible { + /// Type of identifier for inserted elements. + typealias KeyType = BagKey + + typealias Entry = (key: BagKey, value: T) + + private var _nextKey: BagKey = BagKey(rawValue: 0) + + // data + + // first fill inline variables + var _key0: BagKey? + var _value0: T? + + // then fill "array dictionary" + var _pairs = ContiguousArray() + + // last is sparse dictionary + var _dictionary: [BagKey: T]? + + var _onlyFastPath = true + + /// Creates new empty `Bag`. + init() { + } + + /** + Inserts `value` into bag. + + - parameter element: Element to insert. + - returns: Key that can be used to remove element from bag. + */ + mutating func insert(_ element: T) -> BagKey { + let key = _nextKey + + _nextKey = BagKey(rawValue: _nextKey.rawValue &+ 1) + + if _key0 == nil { + _key0 = key + _value0 = element + return key + } + + _onlyFastPath = false + + if _dictionary != nil { + _dictionary![key] = element + return key + } + + if _pairs.count < arrayDictionaryMaxSize { + _pairs.append((key: key, value: element)) + return key + } + + _dictionary = [key: element] + + return key + } + + /// - returns: Number of elements in bag. + var count: Int { + let dictionaryCount: Int = _dictionary?.count ?? 0 + return (_value0 != nil ? 1 : 0) + _pairs.count + dictionaryCount + } + + /// Removes all elements from bag and clears capacity. + mutating func removeAll() { + _key0 = nil + _value0 = nil + + _pairs.removeAll(keepingCapacity: false) + _dictionary?.removeAll(keepingCapacity: false) + } + + /** + Removes element with a specific `key` from bag. + + - parameter key: Key that identifies element to remove from bag. + - returns: Element that bag contained, or nil in case element was already removed. + */ + mutating func removeKey(_ key: BagKey) -> T? { + if _key0 == key { + _key0 = nil + let value = _value0! + _value0 = nil + return value + } + + if let existingObject = _dictionary?.removeValue(forKey: key) { + return existingObject + } + + for i in 0 ..< _pairs.count where _pairs[i].key == key { + let value = _pairs[i].value + _pairs.remove(at: i) + return value + } + + return nil + } +} + +extension Bag { + /// A textual representation of `self`, suitable for debugging. + var debugDescription : String { + "\(self.count) elements in Bag" + } +} + +extension Bag { + /// Enumerates elements inside the bag. + /// + /// - parameter action: Enumeration closure. + func forEach(_ action: (T) -> Void) { + if _onlyFastPath { + if let value0 = _value0 { + action(value0) + } + return + } + + let value0 = _value0 + let dictionary = _dictionary + + if let value0 = value0 { + action(value0) + } + + for i in 0 ..< _pairs.count { + action(_pairs[i].value) + } + + if dictionary?.count ?? 0 > 0 { + for element in dictionary!.values { + action(element) + } + } + } +} + +extension BagKey: Hashable { + func hash(into hasher: inout Hasher) { + hasher.combine(rawValue) + } +} + +func ==(lhs: BagKey, rhs: BagKey) -> Bool { + lhs.rawValue == rhs.rawValue +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DataStructures/InfiniteSequence.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DataStructures/InfiniteSequence.swift new file mode 100644 index 000000000..75d7bea7f --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DataStructures/InfiniteSequence.swift @@ -0,0 +1,23 @@ +// +// InfiniteSequence.swift +// Platform +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Sequence that repeats `repeatedValue` infinite number of times. +struct InfiniteSequence : Sequence { + typealias Iterator = AnyIterator + + private let repeatedValue: Element + + init(repeatedValue: Element) { + self.repeatedValue = repeatedValue + } + + func makeIterator() -> Iterator { + let repeatedValue = self.repeatedValue + return AnyIterator { repeatedValue } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DataStructures/PriorityQueue.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DataStructures/PriorityQueue.swift new file mode 100644 index 000000000..9ed856b91 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DataStructures/PriorityQueue.swift @@ -0,0 +1,111 @@ +// +// PriorityQueue.swift +// Platform +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct PriorityQueue { + private let hasHigherPriority: (Element, Element) -> Bool + private let isEqual: (Element, Element) -> Bool + + private var elements = [Element]() + + init(hasHigherPriority: @escaping (Element, Element) -> Bool, isEqual: @escaping (Element, Element) -> Bool) { + self.hasHigherPriority = hasHigherPriority + self.isEqual = isEqual + } + + mutating func enqueue(_ element: Element) { + elements.append(element) + bubbleToHigherPriority(elements.count - 1) + } + + func peek() -> Element? { + elements.first + } + + var isEmpty: Bool { + elements.count == 0 + } + + mutating func dequeue() -> Element? { + guard let front = peek() else { + return nil + } + + removeAt(0) + + return front + } + + mutating func remove(_ element: Element) { + for i in 0 ..< elements.count { + if self.isEqual(elements[i], element) { + removeAt(i) + return + } + } + } + + private mutating func removeAt(_ index: Int) { + let removingLast = index == elements.count - 1 + if !removingLast { + elements.swapAt(index, elements.count - 1) + } + + _ = elements.popLast() + + if !removingLast { + bubbleToHigherPriority(index) + bubbleToLowerPriority(index) + } + } + + private mutating func bubbleToHigherPriority(_ initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < elements.count) + + var unbalancedIndex = initialUnbalancedIndex + + while unbalancedIndex > 0 { + let parentIndex = (unbalancedIndex - 1) / 2 + guard self.hasHigherPriority(elements[unbalancedIndex], elements[parentIndex]) else { break } + elements.swapAt(unbalancedIndex, parentIndex) + unbalancedIndex = parentIndex + } + } + + private mutating func bubbleToLowerPriority(_ initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < elements.count) + + var unbalancedIndex = initialUnbalancedIndex + while true { + let leftChildIndex = unbalancedIndex * 2 + 1 + let rightChildIndex = unbalancedIndex * 2 + 2 + + var highestPriorityIndex = unbalancedIndex + + if leftChildIndex < elements.count && self.hasHigherPriority(elements[leftChildIndex], elements[highestPriorityIndex]) { + highestPriorityIndex = leftChildIndex + } + + if rightChildIndex < elements.count && self.hasHigherPriority(elements[rightChildIndex], elements[highestPriorityIndex]) { + highestPriorityIndex = rightChildIndex + } + + guard highestPriorityIndex != unbalancedIndex else { break } + elements.swapAt(highestPriorityIndex, unbalancedIndex) + + unbalancedIndex = highestPriorityIndex + } + } +} + +extension PriorityQueue : CustomDebugStringConvertible { + var debugDescription: String { + elements.debugDescription + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DataStructures/Queue.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DataStructures/Queue.swift new file mode 100644 index 000000000..625d4733e --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DataStructures/Queue.swift @@ -0,0 +1,148 @@ +// +// Queue.swift +// Platform +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Data structure that represents queue. + +Complexity of `enqueue`, `dequeue` is O(1) when number of operations is +averaged over N operations. + +Complexity of `peek` is O(1). +*/ +struct Queue: Sequence { + /// Type of generator. + typealias Generator = AnyIterator + + private let resizeFactor = 2 + + private var storage: ContiguousArray + private var innerCount = 0 + private var pushNextIndex = 0 + private let initialCapacity: Int + + /** + Creates new queue. + + - parameter capacity: Capacity of newly created queue. + */ + init(capacity: Int) { + initialCapacity = capacity + + storage = ContiguousArray(repeating: nil, count: capacity) + } + + private var dequeueIndex: Int { + let index = pushNextIndex - count + return index < 0 ? index + storage.count : index + } + + /// - returns: Is queue empty. + var isEmpty: Bool { count == 0 } + + /// - returns: Number of elements inside queue. + var count: Int { innerCount } + + /// - returns: Element in front of a list of elements to `dequeue`. + func peek() -> T { + precondition(count > 0) + + return storage[dequeueIndex]! + } + + mutating private func resizeTo(_ size: Int) { + var newStorage = ContiguousArray(repeating: nil, count: size) + + let count = self.count + + let dequeueIndex = self.dequeueIndex + let spaceToEndOfQueue = storage.count - dequeueIndex + + // first batch is from dequeue index to end of array + let countElementsInFirstBatch = Swift.min(count, spaceToEndOfQueue) + // second batch is wrapped from start of array to end of queue + let numberOfElementsInSecondBatch = count - countElementsInFirstBatch + + newStorage[0 ..< countElementsInFirstBatch] = storage[dequeueIndex ..< (dequeueIndex + countElementsInFirstBatch)] + newStorage[countElementsInFirstBatch ..< (countElementsInFirstBatch + numberOfElementsInSecondBatch)] = storage[0 ..< numberOfElementsInSecondBatch] + + self.innerCount = count + pushNextIndex = count + storage = newStorage + } + + /// Enqueues `element`. + /// + /// - parameter element: Element to enqueue. + mutating func enqueue(_ element: T) { + if count == storage.count { + resizeTo(Swift.max(storage.count, 1) * resizeFactor) + } + + storage[pushNextIndex] = element + pushNextIndex += 1 + innerCount += 1 + + if pushNextIndex >= storage.count { + pushNextIndex -= storage.count + } + } + + private mutating func dequeueElementOnly() -> T { + precondition(count > 0) + + let index = dequeueIndex + + defer { + storage[index] = nil + innerCount -= 1 + } + + return storage[index]! + } + + /// Dequeues element or throws an exception in case queue is empty. + /// + /// - returns: Dequeued element. + mutating func dequeue() -> T? { + if self.count == 0 { + return nil + } + + defer { + let downsizeLimit = storage.count / (resizeFactor * resizeFactor) + if count < downsizeLimit && downsizeLimit >= initialCapacity { + resizeTo(storage.count / resizeFactor) + } + } + + return dequeueElementOnly() + } + + /// - returns: Generator of contained elements. + func makeIterator() -> AnyIterator { + var i = dequeueIndex + var innerCount = count + + return AnyIterator { + if innerCount == 0 { + return nil + } + + defer { + innerCount -= 1 + i += 1 + } + + if i >= self.storage.count { + i -= self.storage.count + } + + return self.storage[i] + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DispatchQueue+Extensions.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DispatchQueue+Extensions.swift new file mode 100644 index 000000000..aaf24cae6 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/DispatchQueue+Extensions.swift @@ -0,0 +1,21 @@ +// +// DispatchQueue+Extensions.swift +// Platform +// +// Created by Krunoslav Zaher on 10/22/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Dispatch + +extension DispatchQueue { + private static var token: DispatchSpecificKey<()> = { + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + return key + }() + + static var isMain: Bool { + DispatchQueue.getSpecific(key: token) != nil + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/Platform.Darwin.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/Platform.Darwin.swift new file mode 100644 index 000000000..eacc19431 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/Platform.Darwin.swift @@ -0,0 +1,35 @@ +// +// Platform.Darwin.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) + + import Darwin + import Foundation + + extension Thread { + static func setThreadLocalStorageValue(_ value: T?, forKey key: NSCopying) { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + if let newValue = value { + threadDictionary[key] = newValue + } + else { + threadDictionary[key] = nil + } + } + + static func getThreadLocalStorageValueForKey(_ key: NSCopying) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/Platform.Linux.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/Platform.Linux.swift new file mode 100644 index 000000000..52a3e3af8 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/Platform.Linux.swift @@ -0,0 +1,32 @@ +// +// Platform.Linux.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(Linux) + + import Foundation + + extension Thread { + + static func setThreadLocalStorageValue(_ value: T?, forKey key: String) { + if let newValue = value { + Thread.current.threadDictionary[key] = newValue + } + else { + Thread.current.threadDictionary[key] = nil + } + } + + static func getThreadLocalStorageValueForKey(_ key: String) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/RecursiveLock.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/RecursiveLock.swift new file mode 100644 index 000000000..10b9bbb0b --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Platform/RecursiveLock.swift @@ -0,0 +1,34 @@ +// +// RecursiveLock.swift +// Platform +// +// Created by Krunoslav Zaher on 12/18/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +#if TRACE_RESOURCES + class RecursiveLock: NSRecursiveLock { + override init() { + _ = Resources.incrementTotal() + super.init() + } + + override func lock() { + super.lock() + _ = Resources.incrementTotal() + } + + override func unlock() { + super.unlock() + _ = Resources.decrementTotal() + } + + deinit { + _ = Resources.decrementTotal() + } + } +#else + typealias RecursiveLock = NSRecursiveLock +#endif diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Reactive.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Reactive.swift new file mode 100644 index 000000000..1bf390dc5 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Reactive.swift @@ -0,0 +1,80 @@ +// +// Reactive.swift +// RxSwift +// +// Created by Yury Korolev on 5/2/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +/** + Use `Reactive` proxy as customization point for constrained protocol extensions. + + General pattern would be: + + // 1. Extend Reactive protocol with constrain on Base + // Read as: Reactive Extension where Base is a SomeType + extension Reactive where Base: SomeType { + // 2. Put any specific reactive extension for SomeType here + } + + With this approach we can have more specialized methods and properties using + `Base` and not just specialized on common base type. + + `Binder`s are also automatically synthesized using `@dynamicMemberLookup` for writable reference properties of the reactive base. + */ + +@dynamicMemberLookup +public struct Reactive { + /// Base object to extend. + public let base: Base + + /// Creates extensions with base object. + /// + /// - parameter base: Base object. + public init(_ base: Base) { + self.base = base + } + + /// Automatically synthesized binder for a key path between the reactive + /// base and one of its properties + public subscript(dynamicMember keyPath: ReferenceWritableKeyPath) -> Binder where Base: AnyObject { + Binder(self.base) { base, value in + base[keyPath: keyPath] = value + } + } +} + +/// A type that has reactive extensions. +public protocol ReactiveCompatible { + /// Extended type + associatedtype ReactiveBase + + /// Reactive extensions. + static var rx: Reactive.Type { get set } + + /// Reactive extensions. + var rx: Reactive { get set } +} + +extension ReactiveCompatible { + /// Reactive extensions. + public static var rx: Reactive.Type { + get { Reactive.self } + // this enables using Reactive to "mutate" base type + // swiftlint:disable:next unused_setter_value + set { } + } + + /// Reactive extensions. + public var rx: Reactive { + get { Reactive(self) } + // this enables using Reactive to "mutate" base object + // swiftlint:disable:next unused_setter_value + set { } + } +} + +import Foundation + +/// Extend NSObject with `rx` proxy. +extension NSObject: ReactiveCompatible { } diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Rx.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Rx.swift new file mode 100644 index 000000000..bcdd27947 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Rx.swift @@ -0,0 +1,142 @@ +// +// Rx.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if TRACE_RESOURCES + private let resourceCount = AtomicInt(0) + + /// Resource utilization information + public struct Resources { + /// Counts internal Rx resource allocations (Observables, Observers, Disposables, etc.). This provides a simple way to detect leaks during development. + public static var total: Int32 { + load(resourceCount) + } + + /// Increments `Resources.total` resource count. + /// + /// - returns: New resource count + public static func incrementTotal() -> Int32 { + increment(resourceCount) + } + + /// Decrements `Resources.total` resource count + /// + /// - returns: New resource count + public static func decrementTotal() -> Int32 { + decrement(resourceCount) + } + } +#endif + +/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass. +func rxAbstractMethod(file: StaticString = #file, line: UInt = #line) -> Swift.Never { + rxFatalError("Abstract method", file: file, line: line) +} + +func rxFatalError(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> Swift.Never { + fatalError(lastMessage(), file: file, line: line) +} + +func rxFatalErrorInDebug(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) { + #if DEBUG + fatalError(lastMessage(), file: file, line: line) + #else + print("\(file):\(line): \(lastMessage())") + #endif +} + +func incrementChecked(_ i: inout Int) throws -> Int { + if i == Int.max { + throw RxError.overflow + } + defer { i += 1 } + return i +} + +func decrementChecked(_ i: inout Int) throws -> Int { + if i == Int.min { + throw RxError.overflow + } + defer { i -= 1 } + return i +} + +#if DEBUG + import Foundation + final class SynchronizationTracker { + private let lock = RecursiveLock() + + public enum SynchronizationErrorMessages: String { + case variable = "Two different threads are trying to assign the same `Variable.value` unsynchronized.\n This is undefined behavior because the end result (variable value) is nondeterministic and depends on the \n operating system thread scheduler. This will cause random behavior of your program.\n" + case `default` = "Two different unsynchronized threads are trying to send some event simultaneously.\n This is undefined behavior because the ordering of the effects caused by these events is nondeterministic and depends on the \n operating system thread scheduler. This will result in a random behavior of your program.\n" + } + + private var threads = [UnsafeMutableRawPointer: Int]() + + private func synchronizationError(_ message: String) { + #if FATAL_SYNCHRONIZATION + rxFatalError(message) + #else + print(message) + #endif + } + + func register(synchronizationErrorMessage: SynchronizationErrorMessages) { + self.lock.lock(); defer { self.lock.unlock() } + let pointer = Unmanaged.passUnretained(Thread.current).toOpaque() + let count = (self.threads[pointer] ?? 0) + 1 + + if count > 1 { + self.synchronizationError( + "⚠️ Reentrancy anomaly was detected.\n" + + " > Debugging: To debug this issue you can set a breakpoint in \(#file):\(#line) and observe the call stack.\n" + + " > Problem: This behavior is breaking the observable sequence grammar. `next (error | completed)?`\n" + + " This behavior breaks the grammar because there is overlapping between sequence events.\n" + + " Observable sequence is trying to send an event before sending of previous event has finished.\n" + + " > Interpretation: This could mean that there is some kind of unexpected cyclic dependency in your code,\n" + + " or that the system is not behaving in the expected way.\n" + + " > Remedy: If this is the expected behavior this message can be suppressed by adding `.observe(on:MainScheduler.asyncInstance)`\n" + + " or by enqueuing sequence events in some other way.\n" + ) + } + + self.threads[pointer] = count + + if self.threads.count > 1 { + self.synchronizationError( + "⚠️ Synchronization anomaly was detected.\n" + + " > Debugging: To debug this issue you can set a breakpoint in \(#file):\(#line) and observe the call stack.\n" + + " > Problem: This behavior is breaking the observable sequence grammar. `next (error | completed)?`\n" + + " This behavior breaks the grammar because there is overlapping between sequence events.\n" + + " Observable sequence is trying to send an event before sending of previous event has finished.\n" + + " > Interpretation: " + synchronizationErrorMessage.rawValue + + " > Remedy: If this is the expected behavior this message can be suppressed by adding `.observe(on:MainScheduler.asyncInstance)`\n" + + " or by synchronizing sequence events in some other way.\n" + ) + } + } + + func unregister() { + self.lock.performLocked { + let pointer = Unmanaged.passUnretained(Thread.current).toOpaque() + self.threads[pointer] = (self.threads[pointer] ?? 1) - 1 + if self.threads[pointer] == 0 { + self.threads[pointer] = nil + } + } + } + } + +#endif + +/// RxSwift global hooks +public enum Hooks { + + // Should capture call stack + public static var recordCallStackOnError: Bool = false + +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/RxMutableBox.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/RxMutableBox.swift new file mode 100644 index 000000000..73476c367 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/RxMutableBox.swift @@ -0,0 +1,53 @@ +// +// RxMutableBox.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(Linux) +/// As Swift 5 was released, A patch to `Thread` for Linux +/// changed `threadDictionary` to a `NSMutableDictionary` instead of +/// a `Dictionary`: https://github.com/apple/swift-corelibs-foundation/pull/1762/files +/// +/// This means that on Linux specifically, `RxMutableBox` must be a `NSObject` +/// or it won't be possible to store it in `Thread.threadDictionary`. +/// +/// For more information, read the discussion at: +/// https://github.com/ReactiveX/RxSwift/issues/1911#issuecomment-479723298 +import Foundation + +/// Creates mutable reference wrapper for any type. +final class RxMutableBox: NSObject { + /// Wrapped value + var value: T + + /// Creates reference wrapper for `value`. + /// + /// - parameter value: Value to wrap. + init (_ value: T) { + self.value = value + } +} +#else +/// Creates mutable reference wrapper for any type. +final class RxMutableBox: CustomDebugStringConvertible { + /// Wrapped value + var value: T + + /// Creates reference wrapper for `value`. + /// + /// - parameter value: Value to wrap. + init (_ value: T) { + self.value = value + } +} + +extension RxMutableBox { + /// - returns: Box description. + var debugDescription: String { + "MutatingBox(\(self.value))" + } +} +#endif diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/SchedulerType.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/SchedulerType.swift new file mode 100644 index 000000000..6c8fe4a38 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/SchedulerType.swift @@ -0,0 +1,71 @@ +// +// SchedulerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +// Type that represents time interval in the context of RxSwift. +public typealias RxTimeInterval = DispatchTimeInterval + +/// Type that represents absolute time in the context of RxSwift. +public typealias RxTime = Date + +/// Represents an object that schedules units of work. +public protocol SchedulerType: ImmediateSchedulerType { + + /// - returns: Current time. + var now : RxTime { + get + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable +} + +extension SchedulerType { + + /** + Periodic task will be emulated using recursive scheduling. + + - parameter state: Initial state passed to the action upon the first iteration. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - returns: The disposable object used to cancel the scheduled recurring action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + let schedule = SchedulePeriodicRecursive(scheduler: self, startAfter: startAfter, period: period, action: action, state: state) + + return schedule.start() + } + + func scheduleRecursive(_ state: State, dueTime: RxTimeInterval, action: @escaping (State, AnyRecursiveScheduler) -> Void) -> Disposable { + let scheduler = AnyRecursiveScheduler(scheduler: self, action: action) + + scheduler.schedule(state, dueTime: dueTime) + + return Disposables.create(with: scheduler.dispose) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift new file mode 100644 index 000000000..02c47c917 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift @@ -0,0 +1,82 @@ +// +// ConcurrentDispatchQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/5/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +/// Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. You can also pass a serial dispatch queue, it shouldn't cause any problems. +/// +/// This scheduler is suitable when some work needs to be performed in background. +public class ConcurrentDispatchQueueScheduler: SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + public var now : Date { + Date() + } + + let configuration: DispatchQueueConfiguration + + /// Constructs new `ConcurrentDispatchQueueScheduler` that wraps `queue`. + /// + /// - parameter queue: Target dispatch queue. + /// - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + public init(queue: DispatchQueue, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.configuration = DispatchQueueConfiguration(queue: queue, leeway: leeway) + } + + /// Convenience init for scheduler that wraps one of the global concurrent dispatch queues. + /// + /// - parameter qos: Target global dispatch queue, by quality of service class. + /// - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + public convenience init(qos: DispatchQoS, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.init(queue: DispatchQueue( + label: "rxswift.queue.\(qos)", + qos: qos, + attributes: [DispatchQueue.Attributes.concurrent], + target: nil), + leeway: leeway + ) + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + self.configuration.schedule(state, action: action) + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + self.configuration.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/ConcurrentMainScheduler.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/ConcurrentMainScheduler.swift new file mode 100644 index 000000000..c438d7d4d --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/ConcurrentMainScheduler.swift @@ -0,0 +1,87 @@ +// +// ConcurrentMainScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +/** +Abstracts work that needs to be performed on `MainThread`. In case `schedule` methods are called from main thread, it will perform action immediately without scheduling. + +This scheduler is optimized for `subscribeOn` operator. If you want to observe observable sequence elements on main thread using `observeOn` operator, +`MainScheduler` is more suitable for that purpose. +*/ +public final class ConcurrentMainScheduler : SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + private let mainScheduler: MainScheduler + private let mainQueue: DispatchQueue + + /// - returns: Current time. + public var now: Date { + self.mainScheduler.now as Date + } + + private init(mainScheduler: MainScheduler) { + self.mainQueue = DispatchQueue.main + self.mainScheduler = mainScheduler + } + + /// Singleton instance of `ConcurrentMainScheduler` + public static let instance = ConcurrentMainScheduler(mainScheduler: MainScheduler.instance) + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + if DispatchQueue.isMain { + return action(state) + } + + let cancel = SingleAssignmentDisposable() + + self.mainQueue.async { + if cancel.isDisposed { + return + } + + cancel.setDisposable(action(state)) + } + + return cancel + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + self.mainScheduler.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + self.mainScheduler.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/CurrentThreadScheduler.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/CurrentThreadScheduler.swift new file mode 100644 index 000000000..16a7dd328 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/CurrentThreadScheduler.swift @@ -0,0 +1,131 @@ +// +// CurrentThreadScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +#if os(Linux) + fileprivate enum CurrentThreadSchedulerQueueKey { + fileprivate static let instance = "RxSwift.CurrentThreadScheduler.Queue" + } +#else + private class CurrentThreadSchedulerQueueKey: NSObject, NSCopying { + static let instance = CurrentThreadSchedulerQueueKey() + private override init() { + super.init() + } + + override var hash: Int { + return 0 + } + + public func copy(with zone: NSZone? = nil) -> Any { + return self + } + } +#endif + +/// Represents an object that schedules units of work on the current thread. +/// +/// This is the default scheduler for operators that generate elements. +/// +/// This scheduler is also sometimes called `trampoline scheduler`. +public class CurrentThreadScheduler : ImmediateSchedulerType { + typealias ScheduleQueue = RxMutableBox> + + /// The singleton instance of the current thread scheduler. + public static let instance = CurrentThreadScheduler() + + private static var isScheduleRequiredKey: pthread_key_t = { () -> pthread_key_t in + let key = UnsafeMutablePointer.allocate(capacity: 1) + defer { key.deallocate() } + + guard pthread_key_create(key, nil) == 0 else { + rxFatalError("isScheduleRequired key creation failed") + } + + return key.pointee + }() + + private static var scheduleInProgressSentinel: UnsafeRawPointer = { () -> UnsafeRawPointer in + return UnsafeRawPointer(UnsafeMutablePointer.allocate(capacity: 1)) + }() + + static var queue : ScheduleQueue? { + get { + return Thread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerQueueKey.instance) + } + set { + Thread.setThreadLocalStorageValue(newValue, forKey: CurrentThreadSchedulerQueueKey.instance) + } + } + + /// Gets a value that indicates whether the caller must call a `schedule` method. + public static private(set) var isScheduleRequired: Bool { + get { + return pthread_getspecific(CurrentThreadScheduler.isScheduleRequiredKey) == nil + } + set(isScheduleRequired) { + if pthread_setspecific(CurrentThreadScheduler.isScheduleRequiredKey, isScheduleRequired ? nil : scheduleInProgressSentinel) != 0 { + rxFatalError("pthread_setspecific failed") + } + } + } + + /** + Schedules an action to be executed as soon as possible on current thread. + + If this method is called on some thread that doesn't have `CurrentThreadScheduler` installed, scheduler will be + automatically installed and uninstalled after all work is performed. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + if CurrentThreadScheduler.isScheduleRequired { + CurrentThreadScheduler.isScheduleRequired = false + + let disposable = action(state) + + defer { + CurrentThreadScheduler.isScheduleRequired = true + CurrentThreadScheduler.queue = nil + } + + guard let queue = CurrentThreadScheduler.queue else { + return disposable + } + + while let latest = queue.value.dequeue() { + if latest.isDisposed { + continue + } + latest.invoke() + } + + return disposable + } + + let existingQueue = CurrentThreadScheduler.queue + + let queue: RxMutableBox> + if let existingQueue = existingQueue { + queue = existingQueue + } + else { + queue = RxMutableBox(Queue(capacity: 1)) + CurrentThreadScheduler.queue = queue + } + + let scheduledItem = ScheduledItem(action: action, state: state) + queue.value.enqueue(scheduledItem) + + return scheduledItem + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/HistoricalScheduler.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/HistoricalScheduler.swift new file mode 100644 index 000000000..254a3e83c --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/HistoricalScheduler.swift @@ -0,0 +1,22 @@ +// +// HistoricalScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/// Provides a virtual time scheduler that uses `Date` for absolute time and `TimeInterval` for relative time. +public class HistoricalScheduler : VirtualTimeScheduler { + + /** + Creates a new historical scheduler with initial clock value. + + - parameter initialClock: Initial value for virtual clock. + */ + public init(initialClock: RxTime = Date(timeIntervalSince1970: 0)) { + super.init(initialClock: initialClock, converter: HistoricalSchedulerTimeConverter()) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift new file mode 100644 index 000000000..a8fae8a40 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift @@ -0,0 +1,67 @@ +// +// HistoricalSchedulerTimeConverter.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/// Converts historical virtual time into real time. +/// +/// Since historical virtual time is also measured in `Date`, this converter is identity function. +public struct HistoricalSchedulerTimeConverter : VirtualTimeConverterType { + /// Virtual time unit used that represents ticks of virtual clock. + public typealias VirtualTimeUnit = RxTime + + /// Virtual time unit used to represent differences of virtual times. + public typealias VirtualTimeIntervalUnit = TimeInterval + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertFromVirtualTime(_ virtualTime: VirtualTimeUnit) -> RxTime { + virtualTime + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertToVirtualTime(_ time: RxTime) -> VirtualTimeUnit { + time + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertFromVirtualTimeInterval(_ virtualTimeInterval: VirtualTimeIntervalUnit) -> TimeInterval { + virtualTimeInterval + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertToVirtualTimeInterval(_ timeInterval: TimeInterval) -> VirtualTimeIntervalUnit { + timeInterval + } + + /** + Offsets `Date` by time interval. + + - parameter time: Time. + - parameter timeInterval: Time interval offset. + - returns: Time offsetted by time interval. + */ + public func offsetVirtualTime(_ time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit { + time.addingTimeInterval(offset) + } + + /// Compares two `Date`s. + public func compareVirtualTime(_ lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison { + switch lhs.compare(rhs as Date) { + case .orderedAscending: + return .lessThan + case .orderedSame: + return .equal + case .orderedDescending: + return .greaterThan + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift new file mode 100644 index 000000000..53f148dc4 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift @@ -0,0 +1,97 @@ +// +// DispatchQueueConfiguration.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/23/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +struct DispatchQueueConfiguration { + let queue: DispatchQueue + let leeway: DispatchTimeInterval +} + +extension DispatchQueueConfiguration { + func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let cancel = SingleAssignmentDisposable() + + self.queue.async { + if cancel.isDisposed { + return + } + + + cancel.setDisposable(action(state)) + } + + return cancel + } + + func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let deadline = DispatchTime.now() + dueTime + + let compositeDisposable = CompositeDisposable() + + let timer = DispatchSource.makeTimerSource(queue: self.queue) + timer.schedule(deadline: deadline, leeway: self.leeway) + + // TODO: + // This looks horrible, and yes, it is. + // It looks like Apple has made a conceptual change here, and I'm unsure why. + // Need more info on this. + // It looks like just setting timer to fire and not holding a reference to it + // until deadline causes timer cancellation. + var timerReference: DispatchSourceTimer? = timer + let cancelTimer = Disposables.create { + timerReference?.cancel() + timerReference = nil + } + + timer.setEventHandler(handler: { + if compositeDisposable.isDisposed { + return + } + _ = compositeDisposable.insert(action(state)) + cancelTimer.dispose() + }) + timer.resume() + + _ = compositeDisposable.insert(cancelTimer) + + return compositeDisposable + } + + func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + let initial = DispatchTime.now() + startAfter + + var timerState = state + + let timer = DispatchSource.makeTimerSource(queue: self.queue) + timer.schedule(deadline: initial, repeating: period, leeway: self.leeway) + + // TODO: + // This looks horrible, and yes, it is. + // It looks like Apple has made a conceptual change here, and I'm unsure why. + // Need more info on this. + // It looks like just setting timer to fire and not holding a reference to it + // until deadline causes timer cancellation. + var timerReference: DispatchSourceTimer? = timer + let cancelTimer = Disposables.create { + timerReference?.cancel() + timerReference = nil + } + + timer.setEventHandler(handler: { + if cancelTimer.isDisposed { + return + } + timerState = action(timerState) + }) + timer.resume() + + return cancelTimer + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift new file mode 100644 index 000000000..0e1505610 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift @@ -0,0 +1,22 @@ +// +// InvocableScheduledItem.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct InvocableScheduledItem : InvocableType { + + let invocable: I + let state: I.Value + + init(invocable: I, state: I.Value) { + self.invocable = invocable + self.state = state + } + + func invoke() { + self.invocable.invoke(self.state) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/InvocableType.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/InvocableType.swift new file mode 100644 index 000000000..0dba4336a --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/InvocableType.swift @@ -0,0 +1,17 @@ +// +// InvocableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol InvocableType { + func invoke() +} + +protocol InvocableWithValueType { + associatedtype Value + + func invoke(_ value: Value) +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/ScheduledItem.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/ScheduledItem.swift new file mode 100644 index 000000000..3d790d7af --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/ScheduledItem.swift @@ -0,0 +1,35 @@ +// +// ScheduledItem.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct ScheduledItem + : ScheduledItemType + , InvocableType { + typealias Action = (T) -> Disposable + + private let action: Action + private let state: T + + private let disposable = SingleAssignmentDisposable() + + var isDisposed: Bool { + self.disposable.isDisposed + } + + init(action: @escaping Action, state: T) { + self.action = action + self.state = state + } + + func invoke() { + self.disposable.setDisposable(self.action(self.state)) + } + + func dispose() { + self.disposable.dispose() + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/ScheduledItemType.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/ScheduledItemType.swift new file mode 100644 index 000000000..d2b16cab7 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/Internal/ScheduledItemType.swift @@ -0,0 +1,13 @@ +// +// ScheduledItemType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol ScheduledItemType + : Cancelable + , InvocableType { + func invoke() +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/MainScheduler.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/MainScheduler.swift new file mode 100644 index 000000000..f6a507f3f --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/MainScheduler.swift @@ -0,0 +1,80 @@ +// +// MainScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +#if !os(Linux) + import Foundation +#endif + +/** +Abstracts work that needs to be performed on `DispatchQueue.main`. In case `schedule` methods are called from `DispatchQueue.main`, it will perform action immediately without scheduling. + +This scheduler is usually used to perform UI work. + +Main scheduler is a specialization of `SerialDispatchQueueScheduler`. + +This scheduler is optimized for `observeOn` operator. To ensure observable sequence is subscribed on main thread using `subscribeOn` +operator please use `ConcurrentMainScheduler` because it is more optimized for that purpose. +*/ +public final class MainScheduler : SerialDispatchQueueScheduler { + + private let mainQueue: DispatchQueue + + let numberEnqueued = AtomicInt(0) + + /// Initializes new instance of `MainScheduler`. + public init() { + self.mainQueue = DispatchQueue.main + super.init(serialQueue: self.mainQueue) + } + + /// Singleton instance of `MainScheduler` + public static let instance = MainScheduler() + + /// Singleton instance of `MainScheduler` that always schedules work asynchronously + /// and doesn't perform optimizations for calls scheduled from main queue. + public static let asyncInstance = SerialDispatchQueueScheduler(serialQueue: DispatchQueue.main) + + /// In case this method is called on a background thread it will throw an exception. + public static func ensureExecutingOnScheduler(errorMessage: String? = nil) { + if !DispatchQueue.isMain { + rxFatalError(errorMessage ?? "Executing on background thread. Please use `MainScheduler.instance.schedule` to schedule work on main thread.") + } + } + + /// In case this method is running on a background thread it will throw an exception. + public static func ensureRunningOnMainThread(errorMessage: String? = nil) { + #if !os(Linux) // isMainThread is not implemented in Linux Foundation + guard Thread.isMainThread else { + rxFatalError(errorMessage ?? "Running on background thread.") + } + #endif + } + + override func scheduleInternal(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let previousNumberEnqueued = increment(self.numberEnqueued) + + if DispatchQueue.isMain && previousNumberEnqueued == 0 { + let disposable = action(state) + decrement(self.numberEnqueued) + return disposable + } + + let cancel = SingleAssignmentDisposable() + + self.mainQueue.async { + if !cancel.isDisposed { + cancel.setDisposable(action(state)) + } + + decrement(self.numberEnqueued) + } + + return cancel + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/OperationQueueScheduler.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/OperationQueueScheduler.swift new file mode 100644 index 000000000..f0ad3d3ce --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/OperationQueueScheduler.swift @@ -0,0 +1,54 @@ +// +// OperationQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +/// Abstracts the work that needs to be performed on a specific `NSOperationQueue`. +/// +/// This scheduler is suitable for cases when there is some bigger chunk of work that needs to be performed in background and you want to fine tune concurrent processing using `maxConcurrentOperationCount`. +public class OperationQueueScheduler: ImmediateSchedulerType { + public let operationQueue: OperationQueue + public let queuePriority: Operation.QueuePriority + + /// Constructs new instance of `OperationQueueScheduler` that performs work on `operationQueue`. + /// + /// - parameter operationQueue: Operation queue targeted to perform work on. + /// - parameter queuePriority: Queue priority which will be assigned to new operations. + public init(operationQueue: OperationQueue, queuePriority: Operation.QueuePriority = .normal) { + self.operationQueue = operationQueue + self.queuePriority = queuePriority + } + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let cancel = SingleAssignmentDisposable() + + let operation = BlockOperation { + if cancel.isDisposed { + return + } + + + cancel.setDisposable(action(state)) + } + + operation.queuePriority = self.queuePriority + + self.operationQueue.addOperation(operation) + + return cancel + } + +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/RecursiveScheduler.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/RecursiveScheduler.swift new file mode 100644 index 000000000..0ee78cd18 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/RecursiveScheduler.swift @@ -0,0 +1,220 @@ +// +// RecursiveScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +private enum ScheduleState { + case initial + case added(CompositeDisposable.DisposeKey) + case done +} + +/// Type erased recursive scheduler. +final class AnyRecursiveScheduler { + + typealias Action = (State, AnyRecursiveScheduler) -> Void + + private let lock = RecursiveLock() + + // state + private let group = CompositeDisposable() + + private var scheduler: SchedulerType + private var action: Action? + + init(scheduler: SchedulerType, action: @escaping Action) { + self.action = action + self.scheduler = scheduler + } + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the recursive action. + */ + func schedule(_ state: State, dueTime: RxTimeInterval) { + var scheduleState: ScheduleState = .initial + + let d = self.scheduler.scheduleRelative(state, dueTime: dueTime) { state -> Disposable in + // best effort + if self.group.isDisposed { + return Disposables.create() + } + + let action = self.lock.performLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self.group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self.action + } + + if let action = action { + action(state, self) + } + + return Disposables.create() + } + + self.lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + case .initial: + if let removeKey = self.group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + case .done: + break + } + } + } + + /// Schedules an action to be executed recursively. + /// + /// - parameter state: State passed to the action to be executed. + func schedule(_ state: State) { + var scheduleState: ScheduleState = .initial + + let d = self.scheduler.schedule(state) { state -> Disposable in + // best effort + if self.group.isDisposed { + return Disposables.create() + } + + let action = self.lock.performLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self.group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self.action + } + + if let action = action { + action(state, self) + } + + return Disposables.create() + } + + self.lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + case .initial: + if let removeKey = self.group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + case .done: + break + } + } + } + + func dispose() { + self.lock.performLocked { + self.action = nil + } + self.group.dispose() + } +} + +/// Type erased recursive scheduler. +final class RecursiveImmediateScheduler { + typealias Action = (_ state: State, _ recurse: (State) -> Void) -> Void + + private var lock = SpinLock() + private let group = CompositeDisposable() + + private var action: Action? + private let scheduler: ImmediateSchedulerType + + init(action: @escaping Action, scheduler: ImmediateSchedulerType) { + self.action = action + self.scheduler = scheduler + } + + // immediate scheduling + + /// Schedules an action to be executed recursively. + /// + /// - parameter state: State passed to the action to be executed. + func schedule(_ state: State) { + var scheduleState: ScheduleState = .initial + + let d = self.scheduler.schedule(state) { state -> Disposable in + // best effort + if self.group.isDisposed { + return Disposables.create() + } + + let action = self.lock.performLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self.group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self.action + } + + if let action = action { + action(state, self.schedule) + } + + return Disposables.create() + } + + self.lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + case .initial: + if let removeKey = self.group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + case .done: + break + } + } + } + + func dispose() { + self.lock.performLocked { + self.action = nil + } + self.group.dispose() + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/SchedulerServices+Emulation.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/SchedulerServices+Emulation.swift new file mode 100644 index 000000000..cab2bc8b3 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/SchedulerServices+Emulation.swift @@ -0,0 +1,61 @@ +// +// SchedulerServices+Emulation.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +enum SchedulePeriodicRecursiveCommand { + case tick + case dispatchStart +} + +final class SchedulePeriodicRecursive { + typealias RecursiveAction = (State) -> State + typealias RecursiveScheduler = AnyRecursiveScheduler + + private let scheduler: SchedulerType + private let startAfter: RxTimeInterval + private let period: RxTimeInterval + private let action: RecursiveAction + + private var state: State + private let pendingTickCount = AtomicInt(0) + + init(scheduler: SchedulerType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping RecursiveAction, state: State) { + self.scheduler = scheduler + self.startAfter = startAfter + self.period = period + self.action = action + self.state = state + } + + func start() -> Disposable { + self.scheduler.scheduleRecursive(SchedulePeriodicRecursiveCommand.tick, dueTime: self.startAfter, action: self.tick) + } + + func tick(_ command: SchedulePeriodicRecursiveCommand, scheduler: RecursiveScheduler) { + // Tries to emulate periodic scheduling as best as possible. + // The problem that could arise is if handling periodic ticks take too long, or + // tick interval is short. + switch command { + case .tick: + scheduler.schedule(.tick, dueTime: self.period) + + // The idea is that if on tick there wasn't any item enqueued, schedule to perform work immediately. + // Else work will be scheduled after previous enqueued work completes. + if increment(self.pendingTickCount) == 0 { + self.tick(.dispatchStart, scheduler: scheduler) + } + + case .dispatchStart: + self.state = self.action(self.state) + // Start work and schedule check is this last batch of work + if decrement(self.pendingTickCount) > 1 { + // This gives priority to scheduler emulation, it's not perfect, but helps + scheduler.schedule(SchedulePeriodicRecursiveCommand.dispatchStart) + } + } + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift new file mode 100644 index 000000000..bb0013c8f --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift @@ -0,0 +1,131 @@ +// +// SerialDispatchQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +/** +Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. It will make sure +that even if concurrent dispatch queue is passed, it's transformed into a serial one. + +It is extremely important that this scheduler is serial, because +certain operator perform optimizations that rely on that property. + +Because there is no way of detecting is passed dispatch queue serial or +concurrent, for every queue that is being passed, worst case (concurrent) +will be assumed, and internal serial proxy dispatch queue will be created. + +This scheduler can also be used with internal serial queue alone. + +In case some customization need to be made on it before usage, +internal serial queue can be customized using `serialQueueConfiguration` +callback. +*/ +public class SerialDispatchQueueScheduler : SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + /// - returns: Current time. + public var now : Date { + Date() + } + + let configuration: DispatchQueueConfiguration + + /** + Constructs new `SerialDispatchQueueScheduler` that wraps `serialQueue`. + + - parameter serialQueue: Target dispatch queue. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + init(serialQueue: DispatchQueue, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.configuration = DispatchQueueConfiguration(queue: serialQueue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` with internal serial queue named `internalSerialQueueName`. + + Additional dispatch queue properties can be set after dispatch queue is created using `serialQueueConfiguration`. + + - parameter internalSerialQueueName: Name of internal serial dispatch queue. + - parameter serialQueueConfiguration: Additional configuration of internal serial dispatch queue. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + public convenience init(internalSerialQueueName: String, serialQueueConfiguration: ((DispatchQueue) -> Void)? = nil, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + let queue = DispatchQueue(label: internalSerialQueueName, attributes: []) + serialQueueConfiguration?(queue) + self.init(serialQueue: queue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` named `internalSerialQueueName` that wraps `queue`. + + - parameter queue: Possibly concurrent dispatch queue used to perform work. + - parameter internalSerialQueueName: Name of internal serial dispatch queue proxy. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + public convenience init(queue: DispatchQueue, internalSerialQueueName: String, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + // Swift 3.0 IUO + let serialQueue = DispatchQueue(label: internalSerialQueueName, + attributes: [], + target: queue) + self.init(serialQueue: serialQueue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` that wraps one of the global concurrent dispatch queues. + + - parameter qos: Identifier for global dispatch queue with specified quality of service class. + - parameter internalSerialQueueName: Custom name for internal serial dispatch queue proxy. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + @available(macOS 10.10, *) + public convenience init(qos: DispatchQoS, internalSerialQueueName: String = "rx.global_dispatch_queue.serial", leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.init(queue: DispatchQueue.global(qos: qos.qosClass), internalSerialQueueName: internalSerialQueueName, leeway: leeway) + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + self.scheduleInternal(state, action: action) + } + + func scheduleInternal(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + self.configuration.schedule(state, action: action) + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + self.configuration.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/VirtualTimeConverterType.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/VirtualTimeConverterType.swift new file mode 100644 index 000000000..9592d6e3f --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/VirtualTimeConverterType.swift @@ -0,0 +1,97 @@ +// +// VirtualTimeConverterType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/// Parametrization for virtual time used by `VirtualTimeScheduler`s. +public protocol VirtualTimeConverterType { + /// Virtual time unit used that represents ticks of virtual clock. + associatedtype VirtualTimeUnit + + /// Virtual time unit used to represent differences of virtual times. + associatedtype VirtualTimeIntervalUnit + + /** + Converts virtual time to real time. + + - parameter virtualTime: Virtual time to convert to `Date`. + - returns: `Date` corresponding to virtual time. + */ + func convertFromVirtualTime(_ virtualTime: VirtualTimeUnit) -> RxTime + + /** + Converts real time to virtual time. + + - parameter time: `Date` to convert to virtual time. + - returns: Virtual time corresponding to `Date`. + */ + func convertToVirtualTime(_ time: RxTime) -> VirtualTimeUnit + + /** + Converts from virtual time interval to `TimeInterval`. + + - parameter virtualTimeInterval: Virtual time interval to convert to `TimeInterval`. + - returns: `TimeInterval` corresponding to virtual time interval. + */ + func convertFromVirtualTimeInterval(_ virtualTimeInterval: VirtualTimeIntervalUnit) -> TimeInterval + + /** + Converts from `TimeInterval` to virtual time interval. + + - parameter timeInterval: `TimeInterval` to convert to virtual time interval. + - returns: Virtual time interval corresponding to time interval. + */ + func convertToVirtualTimeInterval(_ timeInterval: TimeInterval) -> VirtualTimeIntervalUnit + + /** + Offsets virtual time by virtual time interval. + + - parameter time: Virtual time. + - parameter offset: Virtual time interval. + - returns: Time corresponding to time offsetted by virtual time interval. + */ + func offsetVirtualTime(_ time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit + + /** + This is additional abstraction because `Date` is unfortunately not comparable. + Extending `Date` with `Comparable` would be too risky because of possible collisions with other libraries. + */ + func compareVirtualTime(_ lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison +} + +/** + Virtual time comparison result. + + This is additional abstraction because `Date` is unfortunately not comparable. + Extending `Date` with `Comparable` would be too risky because of possible collisions with other libraries. +*/ +public enum VirtualTimeComparison { + /// lhs < rhs. + case lessThan + /// lhs == rhs. + case equal + /// lhs > rhs. + case greaterThan +} + +extension VirtualTimeComparison { + /// lhs < rhs. + var lessThen: Bool { + self == .lessThan + } + + /// lhs > rhs + var greaterThan: Bool { + self == .greaterThan + } + + /// lhs == rhs + var equal: Bool { + self == .equal + } +} diff --git a/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/VirtualTimeScheduler.swift b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/VirtualTimeScheduler.swift new file mode 100644 index 000000000..e74d5be69 --- /dev/null +++ b/ios/MultiPlatformBleAdapter/iOS/RxSwift/Schedulers/VirtualTimeScheduler.swift @@ -0,0 +1,267 @@ +// +// VirtualTimeScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Base class for virtual time schedulers using a priority queue for scheduled items. +open class VirtualTimeScheduler + : SchedulerType { + + public typealias VirtualTime = Converter.VirtualTimeUnit + public typealias VirtualTimeInterval = Converter.VirtualTimeIntervalUnit + + private var running : Bool + + private var currentClock: VirtualTime + + private var schedulerQueue : PriorityQueue> + private var converter: Converter + + private var nextId = 0 + + /// - returns: Current time. + public var now: RxTime { + self.converter.convertFromVirtualTime(self.clock) + } + + /// - returns: Scheduler's absolute time clock value. + public var clock: VirtualTime { + self.currentClock + } + + /// Creates a new virtual time scheduler. + /// + /// - parameter initialClock: Initial value for the clock. + public init(initialClock: VirtualTime, converter: Converter) { + self.currentClock = initialClock + self.running = false + self.converter = converter + self.schedulerQueue = PriorityQueue(hasHigherPriority: { + switch converter.compareVirtualTime($0.time, $1.time) { + case .lessThan: + return true + case .equal: + return $0.id < $1.id + case .greaterThan: + return false + } + }, isEqual: { $0 === $1 }) + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + return self.scheduleRelative(state, dueTime: .microseconds(0)) { a in + return action(a) + } + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let time = self.now.addingDispatchInterval(dueTime) + let absoluteTime = self.converter.convertToVirtualTime(time) + let adjustedTime = self.adjustScheduledTime(absoluteTime) + return self.scheduleAbsoluteVirtual(state, time: adjustedTime, action: action) + } + + /** + Schedules an action to be executed after relative time has passed. + + - parameter state: State passed to the action to be executed. + - parameter time: Absolute time when to execute the action. If this is less or equal then `now`, `now + 1` will be used. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRelativeVirtual(_ state: StateType, dueTime: VirtualTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let time = self.converter.offsetVirtualTime(self.clock, offset: dueTime) + return self.scheduleAbsoluteVirtual(state, time: time, action: action) + } + + /** + Schedules an action to be executed at absolute virtual time. + + - parameter state: State passed to the action to be executed. + - parameter time: Absolute time when to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleAbsoluteVirtual(_ state: StateType, time: VirtualTime, action: @escaping (StateType) -> Disposable) -> Disposable { + MainScheduler.ensureExecutingOnScheduler() + + let compositeDisposable = CompositeDisposable() + + let item = VirtualSchedulerItem(action: { + return action(state) + }, time: time, id: self.nextId) + + self.nextId += 1 + + self.schedulerQueue.enqueue(item) + + _ = compositeDisposable.insert(item) + + return compositeDisposable + } + + /// Adjusts time of scheduling before adding item to schedule queue. + open func adjustScheduledTime(_ time: VirtualTime) -> VirtualTime { + time + } + + /// Starts the virtual time scheduler. + public func start() { + MainScheduler.ensureExecutingOnScheduler() + + if self.running { + return + } + + self.running = true + repeat { + guard let next = self.findNext() else { + break + } + + if self.converter.compareVirtualTime(next.time, self.clock).greaterThan { + self.currentClock = next.time + } + + next.invoke() + self.schedulerQueue.remove(next) + } while self.running + + self.running = false + } + + func findNext() -> VirtualSchedulerItem? { + while let front = self.schedulerQueue.peek() { + if front.isDisposed { + self.schedulerQueue.remove(front) + continue + } + + return front + } + + return nil + } + + /// Advances the scheduler's clock to the specified time, running all work till that point. + /// + /// - parameter virtualTime: Absolute time to advance the scheduler's clock to. + public func advanceTo(_ virtualTime: VirtualTime) { + MainScheduler.ensureExecutingOnScheduler() + + if self.running { + fatalError("Scheduler is already running") + } + + self.running = true + repeat { + guard let next = self.findNext() else { + break + } + + if self.converter.compareVirtualTime(next.time, virtualTime).greaterThan { + break + } + + if self.converter.compareVirtualTime(next.time, self.clock).greaterThan { + self.currentClock = next.time + } + next.invoke() + self.schedulerQueue.remove(next) + } while self.running + + self.currentClock = virtualTime + self.running = false + } + + /// Advances the scheduler's clock by the specified relative time. + public func sleep(_ virtualInterval: VirtualTimeInterval) { + MainScheduler.ensureExecutingOnScheduler() + + let sleepTo = self.converter.offsetVirtualTime(self.clock, offset: virtualInterval) + if self.converter.compareVirtualTime(sleepTo, self.clock).lessThen { + fatalError("Can't sleep to past.") + } + + self.currentClock = sleepTo + } + + /// Stops the virtual time scheduler. + public func stop() { + MainScheduler.ensureExecutingOnScheduler() + + self.running = false + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif +} + +// MARK: description + +extension VirtualTimeScheduler: CustomDebugStringConvertible { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + self.schedulerQueue.debugDescription + } +} + +final class VirtualSchedulerItem