Skip to content

Instantly share code, notes, and snippets.

@Adobels
Last active February 12, 2020 14:35
Show Gist options
  • Save Adobels/0dfc2b596fd4d212056808d88cc94909 to your computer and use it in GitHub Desktop.
Save Adobels/0dfc2b596fd4d212056808d88cc94909 to your computer and use it in GitHub Desktop.
RxSwift 5.0.1 Framework concatenated to a single file
//
// AddRef.swift
// RxSwift
//
// Created by Junior B. on 30/10/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
final class AddRefSink<Observer: ObserverType> : Sink<Observer>, ObserverType {
typealias Element = Observer.Element
override init(observer: Observer, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
switch event {
case .next:
self.forwardOn(event)
case .completed, .error:
self.forwardOn(event)
self.dispose()
}
}
}
final class AddRef<Element> : Producer<Element> {
private let _source: Observable<Element>
private let _refCount: RefCountDisposable
init(source: Observable<Element>, refCount: RefCountDisposable) {
self._source = source
self._refCount = refCount
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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: Swift.Sequence>(_ sequence: Sequence) -> Observable<Element>
where Sequence.Element == Observable<Element> {
return sequence.reduce(Observable<Sequence.Element.Element>.never()) { a, o in
return 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<O2: ObservableType>
(_ right: O2)
-> Observable<Element> where O2.Element == Element {
return Amb(left: self.asObservable(), right: right.asObservable())
}
}
private enum AmbState {
case neither
case left
case right
}
final private class AmbObserver<Observer: ObserverType>: ObserverType {
typealias Element = Observer.Element
typealias Parent = AmbSink<Observer>
typealias This = AmbObserver<Observer>
typealias Sink = (This, Event<Element>) -> 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<Element>) {
self._sink(self, event)
if event.isStopEvent {
self._cancel.dispose()
}
}
deinit {
#if TRACE_RESOURCES
_ = Resources.decrementTotal()
#endif
}
}
final private class AmbSink<Observer: ObserverType>: Sink<Observer> {
typealias Element = Observer.Element
typealias Parent = Amb<Element>
typealias AmbObserverType = AmbObserver<Observer>
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<Element>) -> Void in
self.forwardOn(event)
if event.isStopEvent {
self.dispose()
}
}
let decide = { (o: AmbObserverType, event: Event<Element>, 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<Element>: Producer<Element> {
fileprivate let _left: Observable<Element>
fileprivate let _right: Observable<Element>
init(left: Observable<Element>, right: Observable<Element>) {
self._left = left
self._right = right
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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 _isDisposed = AtomicInt(0)
private var _disposeAction: DisposeAction?
/// - returns: Was resource disposed.
public var isDisposed: Bool {
return isFlagSet(self._isDisposed, 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._isDisposed, 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 {
return AnonymousDisposable(disposeAction: dispose)
}
}
//
// AnonymousObserver.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
final class AnonymousObserver<Element>: ObserverBase<Element> {
typealias EventHandler = (Event<Element>) -> Void
private let _eventHandler : EventHandler
init(_ eventHandler: @escaping EventHandler) {
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
self._eventHandler = eventHandler
}
override func onCore(_ event: Event<Element>) {
return self._eventHandler(event)
}
#if TRACE_RESOURCES
deinit {
_ = Resources.decrementTotal()
}
#endif
}
//
// 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<Element> : ObserverType {
/// Anonymous event handler type.
public typealias EventHandler = (Event<Element>) -> 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: ObserverType>(_ observer: Observer) where Observer.Element == Element {
self.observer = observer.on
}
/// Send `event` to this observer.
///
/// - parameter event: Event instance.
public func on(_ event: Event<Element>) {
return self.observer(event)
}
/// Erases type of observer and returns canonical observer.
///
/// - returns: type erased observer.
public func asObserver() -> AnyObserver<Element> {
return self
}
}
extension AnyObserver {
/// Collection of `AnyObserver`s
typealias s = Bag<(Event<Element>) -> Void>
}
extension ObserverType {
/// Erases type of observer and returns canonical observer.
///
/// - returns: type erased observer.
public func asObserver() -> AnyObserver<Element> {
return 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<Result>(_ transform: @escaping (Result) throws -> Element) -> AnyObserver<Result> {
return AnyObserver { e in
self.on(e.map(transform))
}
}
}
//
// AsMaybe.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/12/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
private final class AsMaybeSink<Observer: ObserverType> : Sink<Observer>, ObserverType {
typealias Element = Observer.Element
private var _element: Event<Element>?
func on(_ event: Event<Element>) {
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<Element>: Producer<Element> {
private let _source: Observable<Element>
init(source: Observable<Element>) {
self._source = source
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// AsSingle.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/12/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
private final class AsSingleSink<Observer: ObserverType> : Sink<Observer>, ObserverType {
typealias Element = Observer.Element
private var _element: Event<Element>?
func on(_ event: Event<Element>) {
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<Element>: Producer<Element> {
private let _source: Observable<Element>
init(source: Observable<Element>) {
self._source = source
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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<I: InvocableType>
: Disposable
, Lock
, SynchronizedDisposeType {
typealias Action = () -> Void
var _lock = SpinLock()
private var _queue: Queue<I> = 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.lock(); defer { self._lock.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.lock(); defer { self._lock.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
}
}
//
// AsyncSubject.swift
// RxSwift
//
// Created by Victor Galán on 07/01/2017.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
/// An AsyncSubject emits the last value (and only the last value) emitted by the source Observable,
/// and only after that source Observable completes.
///
/// (If the source Observable does not emit any values, the AsyncSubject also completes without emitting any values.)
public final class AsyncSubject<Element>
: Observable<Element>
, SubjectType
, ObserverType
, SynchronizedUnsubscribeType {
public typealias SubjectObserverType = AsyncSubject<Element>
typealias Observers = AnyObserver<Element>.s
typealias DisposeKey = Observers.KeyType
/// Indicates whether the subject has any observers
public var hasObservers: Bool {
self._lock.lock(); defer { self._lock.unlock() }
return self._observers.count > 0
}
let _lock = RecursiveLock()
// state
private var _observers = Observers()
private var _isStopped = false
private var _stoppedEvent = nil as Event<Element>? {
didSet {
self._isStopped = self._stoppedEvent != nil
}
}
private var _lastElement: Element?
#if DEBUG
private let _synchronizationTracker = SynchronizationTracker()
#endif
/// Creates a subject.
public override init() {
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
super.init()
}
/// Notifies all subscribed observers about next event.
///
/// - parameter event: Event to send to the observers.
public func on(_ event: Event<Element>) {
#if DEBUG
self._synchronizationTracker.register(synchronizationErrorMessage: .default)
defer { self._synchronizationTracker.unregister() }
#endif
let (observers, event) = self._synchronized_on(event)
switch event {
case .next:
dispatch(observers, event)
dispatch(observers, .completed)
case .completed:
dispatch(observers, event)
case .error:
dispatch(observers, event)
}
}
func _synchronized_on(_ event: Event<Element>) -> (Observers, Event<Element>) {
self._lock.lock(); defer { self._lock.unlock() }
if self._isStopped {
return (Observers(), .completed)
}
switch event {
case .next(let element):
self._lastElement = element
return (Observers(), .completed)
case .error:
self._stoppedEvent = event
let observers = self._observers
self._observers.removeAll()
return (observers, event)
case .completed:
let observers = self._observers
self._observers.removeAll()
if let lastElement = self._lastElement {
self._stoppedEvent = .next(lastElement)
return (observers, .next(lastElement))
}
else {
self._stoppedEvent = event
return (observers, .completed)
}
}
}
/// Subscribes an observer to the subject.
///
/// - parameter observer: Observer to subscribe to the subject.
/// - returns: Disposable object that can be used to unsubscribe the observer from the subject.
public override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
self._lock.lock(); defer { self._lock.unlock() }
return self._synchronized_subscribe(observer)
}
func _synchronized_subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
if let stoppedEvent = self._stoppedEvent {
switch stoppedEvent {
case .next:
observer.on(stoppedEvent)
observer.on(.completed)
case .completed:
observer.on(stoppedEvent)
case .error:
observer.on(stoppedEvent)
}
return Disposables.create()
}
let key = self._observers.insert(observer.on)
return SubscriptionDisposable(owner: self, key: key)
}
func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
self._lock.lock(); defer { self._lock.unlock() }
self._synchronized_unsubscribe(disposeKey)
}
func _synchronized_unsubscribe(_ disposeKey: DisposeKey) {
_ = self._observers.removeKey(disposeKey)
}
/// Returns observer interface for subject.
public func asObserver() -> AsyncSubject<Element> {
return self
}
#if TRACE_RESOURCES
deinit {
_ = Resources.decrementTotal()
}
#endif
}
//
// AtomicInt.swift
// Platform
//
// Created by Krunoslav Zaher on 10/28/18.
// Copyright © 2018 Krunoslav Zaher. All rights reserved.
//
import class Foundation.NSLock
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 {
return add(this, 1)
}
@discardableResult
@inline(__always)
func decrement(_ this: AtomicInt) -> Int32 {
return sub(this, 1)
}
@inline(__always)
func isFlagSet(_ this: AtomicInt, _ mask: Int32) -> Bool {
return (load(this) & mask) != 0
}
//
// 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<Element>(_ bag: Bag<(Event<Element>) -> Void>, _ event: Event<Element>) {
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<Disposable>) {
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()
}
}
}
//
// 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<T> : 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<Entry>()
// 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 {
return "\(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 {
return lhs.rawValue == rhs.rawValue
}
//
// BehaviorSubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/23/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// Represents a value that changes over time.
///
/// Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
public final class BehaviorSubject<Element>
: Observable<Element>
, SubjectType
, ObserverType
, SynchronizedUnsubscribeType
, Cancelable {
public typealias SubjectObserverType = BehaviorSubject<Element>
typealias Observers = AnyObserver<Element>.s
typealias DisposeKey = Observers.KeyType
/// Indicates whether the subject has any observers
public var hasObservers: Bool {
self._lock.lock()
let value = self._observers.count > 0
self._lock.unlock()
return value
}
let _lock = RecursiveLock()
// state
private var _isDisposed = false
private var _element: Element
private var _observers = Observers()
private var _stoppedEvent: Event<Element>?
#if DEBUG
private let _synchronizationTracker = SynchronizationTracker()
#endif
/// Indicates whether the subject has been disposed.
public var isDisposed: Bool {
return self._isDisposed
}
/// Initializes a new instance of the subject that caches its last value and starts with the specified value.
///
/// - parameter value: Initial value sent to observers when no other value has been received by the subject yet.
public init(value: Element) {
self._element = value
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
}
/// Gets the current value or throws an error.
///
/// - returns: Latest value.
public func value() throws -> Element {
self._lock.lock(); defer { self._lock.unlock() } // {
if self._isDisposed {
throw RxError.disposed(object: self)
}
if let error = self._stoppedEvent?.error {
// intentionally throw exception
throw error
}
else {
return self._element
}
//}
}
/// Notifies all subscribed observers about next event.
///
/// - parameter event: Event to send to the observers.
public func on(_ event: Event<Element>) {
#if DEBUG
self._synchronizationTracker.register(synchronizationErrorMessage: .default)
defer { self._synchronizationTracker.unregister() }
#endif
dispatch(self._synchronized_on(event), event)
}
func _synchronized_on(_ event: Event<Element>) -> Observers {
self._lock.lock(); defer { self._lock.unlock() }
if self._stoppedEvent != nil || self._isDisposed {
return Observers()
}
switch event {
case .next(let element):
self._element = element
case .error, .completed:
self._stoppedEvent = event
}
return self._observers
}
/// Subscribes an observer to the subject.
///
/// - parameter observer: Observer to subscribe to the subject.
/// - returns: Disposable object that can be used to unsubscribe the observer from the subject.
public override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
self._lock.lock()
let subscription = self._synchronized_subscribe(observer)
self._lock.unlock()
return subscription
}
func _synchronized_subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
if self._isDisposed {
observer.on(.error(RxError.disposed(object: self)))
return Disposables.create()
}
if let stoppedEvent = self._stoppedEvent {
observer.on(stoppedEvent)
return Disposables.create()
}
let key = self._observers.insert(observer.on)
observer.on(.next(self._element))
return SubscriptionDisposable(owner: self, key: key)
}
func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
self._lock.lock()
self._synchronized_unsubscribe(disposeKey)
self._lock.unlock()
}
func _synchronized_unsubscribe(_ disposeKey: DisposeKey) {
if self._isDisposed {
return
}
_ = self._observers.removeKey(disposeKey)
}
/// Returns observer interface for subject.
public func asObserver() -> BehaviorSubject<Element> {
return self
}
/// Unsubscribe all observers and release resources.
public func dispose() {
self._lock.lock()
self._isDisposed = true
self._observers.removeAll()
self._stoppedEvent = nil
self._lock.unlock()
}
#if TRACE_RESOURCES
deinit {
_ = Resources.decrementTotal()
}
#endif
}
//
// 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 _isDisposed = AtomicInt(0)
// state
private var _disposable1: Disposable?
private var _disposable2: Disposable?
/// - returns: Was resource disposed.
var isDisposed: Bool {
return isFlagSet(self._isDisposed, 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._isDisposed, 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 {
return BinaryDisposable(disposable1, disposable2)
}
}
//
// 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 var _isDisposed = false
/// Initializes a new instance of the `BooleanDisposable` class
public init() {
}
/// Initializes a new instance of the `BooleanDisposable` class with given value
public init(isDisposed: Bool) {
self._isDisposed = isDisposed
}
/// - returns: Was resource disposed.
public var isDisposed: Bool {
return self._isDisposed
}
/// Sets the status to disposed, which can be observer through the `isDisposed` property.
public func dispose() {
self._isDisposed = true
}
}
//
// 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]> {
return BufferTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler)
}
}
final private class BufferTimeCount<Element>: Producer<[Element]> {
fileprivate let _timeSpan: RxTimeInterval
fileprivate let _count: Int
fileprivate let _scheduler: SchedulerType
fileprivate let _source: Observable<Element>
init(source: Observable<Element>, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) {
self._source = source
self._timeSpan = timeSpan
self._count = count
self._scheduler = scheduler
}
override func run<Observer: ObserverType>(_ 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<Element, Observer: ObserverType>
: Sink<Observer>
, LockOwnerType
, ObserverType
, SynchronizedOnType where Observer.Element == [Element] {
typealias Parent = BufferTimeCount<Element>
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<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
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)
}
}
//
// 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 }
}
//
// 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 catchError(_ handler: @escaping (Swift.Error) throws -> Observable<Element>)
-> Observable<Element> {
return Catch(source: self.asObservable(), handler: 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 catchErrorJustReturn(_ element: Element)
-> Observable<Element> {
return Catch(source: self.asObservable(), handler: { _ in Observable.just(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.
*/
public static func catchError<Sequence: Swift.Sequence>(_ sequence: Sequence) -> Observable<Element>
where Sequence.Element == Observable<Element> {
return 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<Element> {
return 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<Element> {
return CatchSequence(sources: Swift.repeatElement(self.asObservable(), count: maxAttemptCount))
}
}
// catch with callback
final private class CatchSinkProxy<Observer: ObserverType>: ObserverType {
typealias Element = Observer.Element
typealias Parent = CatchSink<Observer>
private let _parent: Parent
init(parent: Parent) {
self._parent = parent
}
func on(_ event: Event<Element>) {
self._parent.forwardOn(event)
switch event {
case .next:
break
case .error, .completed:
self._parent.dispose()
}
}
}
final private class CatchSink<Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias Element = Observer.Element
typealias Parent = Catch<Element>
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<Element>) {
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<Element>: Producer<Element> {
typealias Handler = (Swift.Error) throws -> Observable<Element>
fileprivate let _source: Observable<Element>
fileprivate let _handler: Handler
init(source: Observable<Element>, handler: @escaping Handler) {
self._source = source
self._handler = handler
}
override func run<Observer: ObserverType>(_ 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<Sequence: Swift.Sequence, Observer: ObserverType>
: TailRecursiveSink<Sequence, Observer>
, ObserverType where Sequence.Element: ObservableConvertibleType, Sequence.Element.Element == Observer.Element {
typealias Element = Observer.Element
typealias Parent = CatchSequence<Sequence>
private var _lastError: Swift.Error?
override init(observer: Observer, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
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<Element>) -> Disposable {
return 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<Element>) -> SequenceGenerator? {
if let onError = observable as? CatchSequence<Sequence> {
return (onError.sources.makeIterator(), nil)
}
else {
return nil
}
}
}
final private class CatchSequence<Sequence: Swift.Sequence>: Producer<Sequence.Element.Element> where Sequence.Element: ObservableConvertibleType {
typealias Element = Sequence.Element.Element
let sources: Sequence
init(sources: Sequence) {
self.sources = sources
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = CatchSequenceSink<Sequence, Observer>(observer: observer, cancel: cancel)
let subscription = sink.run((self.sources.makeIterator(), nil))
return (sink: sink, subscription: subscription)
}
}
//
// 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: Swift.Collection>(_ collection: Collection, resultSelector: @escaping ([Collection.Element.Element]) throws -> Element) -> Observable<Element>
where Collection.Element: ObservableType {
return 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: Swift.Collection>(_ collection: Collection) -> Observable<[Element]>
where Collection.Element: ObservableType, Collection.Element.Element == Element {
return CombineLatestCollectionType(sources: collection, resultSelector: { $0 })
}
}
final private class CombineLatestCollectionTypeSink<Collection: Swift.Collection, Observer: ObserverType>
: Sink<Observer> where Collection.Element: ObservableConvertibleType {
typealias Result = Observer.Element
typealias Parent = CombineLatestCollectionType<Collection, Result>
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<SourceElement>, 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 private class CombineLatestCollectionType<Collection: Swift.Collection, Result>: Producer<Result> 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: ObserverType>(_ 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)
}
}
// 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<O1: ObservableType, O2: ObservableType>
(_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.Element, O2.Element) throws -> Element)
-> Observable<Element> {
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<O1: ObservableType, O2: ObservableType>
(_ source1: O1, _ source2: O2)
-> Observable<(O1.Element, O2.Element)> {
return CombineLatest2(
source1: source1.asObservable(), source2: source2.asObservable(),
resultSelector: { ($0, $1) }
)
}
}
final class CombineLatestSink2_<E1, E2, Observer: ObserverType> : CombineLatestSink<Observer> {
typealias Result = Observer.Element
typealias Parent = CombineLatest2<E1, E2, Result>
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 {
return try self._parent._resultSelector(self._latestElement1, self._latestElement2)
}
}
final class CombineLatest2<E1, E2, Result> : Producer<Result> {
typealias ResultSelector = (E1, E2) throws -> Result
let _source1: Observable<E1>
let _source2: Observable<E2>
let _resultSelector: ResultSelector
init(source1: Observable<E1>, source2: Observable<E2>, resultSelector: @escaping ResultSelector) {
self._source1 = source1
self._source2 = source2
self._resultSelector = resultSelector
}
override func run<Observer: ObserverType>(_ 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<O1: ObservableType, O2: ObservableType, O3: ObservableType>
(_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.Element, O2.Element, O3.Element) throws -> Element)
-> Observable<Element> {
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<O1: ObservableType, O2: ObservableType, O3: ObservableType>
(_ 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_<E1, E2, E3, Observer: ObserverType> : CombineLatestSink<Observer> {
typealias Result = Observer.Element
typealias Parent = CombineLatest3<E1, E2, E3, Result>
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 {
return try self._parent._resultSelector(self._latestElement1, self._latestElement2, self._latestElement3)
}
}
final class CombineLatest3<E1, E2, E3, Result> : Producer<Result> {
typealias ResultSelector = (E1, E2, E3) throws-> Result
let _source1: Observable<E1>
let _source2: Observable<E2>
let _source3: Observable<E3>
let _resultSelector: ResultSelector
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, resultSelector: @escaping ResultSelector) {
self._source1 = source1
self._source2 = source2
self._source3 = source3
self._resultSelector = resultSelector
}
override func run<Observer: ObserverType>(_ 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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType>
(_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element) throws -> Element)
-> Observable<Element> {
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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType>
(_ 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_<E1, E2, E3, E4, Observer: ObserverType> : CombineLatestSink<Observer> {
typealias Result = Observer.Element
typealias Parent = CombineLatest4<E1, E2, E3, E4, Result>
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 {
return try self._parent._resultSelector(self._latestElement1, self._latestElement2, self._latestElement3, self._latestElement4)
}
}
final class CombineLatest4<E1, E2, E3, E4, Result> : Producer<Result> {
typealias ResultSelector = (E1, E2, E3, E4) throws-> Result
let _source1: Observable<E1>
let _source2: Observable<E2>
let _source3: Observable<E3>
let _source4: Observable<E4>
let _resultSelector: ResultSelector
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, source4: Observable<E4>, resultSelector: @escaping ResultSelector) {
self._source1 = source1
self._source2 = source2
self._source3 = source3
self._source4 = source4
self._resultSelector = resultSelector
}
override func run<Observer: ObserverType>(_ 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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType>
(_ 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<Element> {
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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType>
(_ 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_<E1, E2, E3, E4, E5, Observer: ObserverType> : CombineLatestSink<Observer> {
typealias Result = Observer.Element
typealias Parent = CombineLatest5<E1, E2, E3, E4, E5, Result>
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 {
return try self._parent._resultSelector(self._latestElement1, self._latestElement2, self._latestElement3, self._latestElement4, self._latestElement5)
}
}
final class CombineLatest5<E1, E2, E3, E4, E5, Result> : Producer<Result> {
typealias ResultSelector = (E1, E2, E3, E4, E5) throws-> Result
let _source1: Observable<E1>
let _source2: Observable<E2>
let _source3: Observable<E3>
let _source4: Observable<E4>
let _source5: Observable<E5>
let _resultSelector: ResultSelector
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, source4: Observable<E4>, source5: Observable<E5>, 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: ObserverType>(_ 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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType, O6: ObservableType>
(_ 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<Element> {
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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType, O6: ObservableType>
(_ 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_<E1, E2, E3, E4, E5, E6, Observer: ObserverType> : CombineLatestSink<Observer> {
typealias Result = Observer.Element
typealias Parent = CombineLatest6<E1, E2, E3, E4, E5, E6, Result>
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 {
return try self._parent._resultSelector(self._latestElement1, self._latestElement2, self._latestElement3, self._latestElement4, self._latestElement5, self._latestElement6)
}
}
final class CombineLatest6<E1, E2, E3, E4, E5, E6, Result> : Producer<Result> {
typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws-> Result
let _source1: Observable<E1>
let _source2: Observable<E2>
let _source3: Observable<E3>
let _source4: Observable<E4>
let _source5: Observable<E5>
let _source6: Observable<E6>
let _resultSelector: ResultSelector
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, source4: Observable<E4>, source5: Observable<E5>, source6: Observable<E6>, 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: ObserverType>(_ 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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType, O6: ObservableType, O7: ObservableType>
(_ 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<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: 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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType, O6: ObservableType, O7: ObservableType>
(_ 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_<E1, E2, E3, E4, E5, E6, E7, Observer: ObserverType> : CombineLatestSink<Observer> {
typealias Result = Observer.Element
typealias Parent = CombineLatest7<E1, E2, E3, E4, E5, E6, E7, Result>
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 {
return try self._parent._resultSelector(self._latestElement1, self._latestElement2, self._latestElement3, self._latestElement4, self._latestElement5, self._latestElement6, self._latestElement7)
}
}
final class CombineLatest7<E1, E2, E3, E4, E5, E6, E7, Result> : Producer<Result> {
typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws-> Result
let _source1: Observable<E1>
let _source2: Observable<E2>
let _source3: Observable<E3>
let _source4: Observable<E4>
let _source5: Observable<E5>
let _source6: Observable<E6>
let _source7: Observable<E7>
let _resultSelector: ResultSelector
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, source4: Observable<E4>, source5: Observable<E5>, source6: Observable<E6>, source7: Observable<E7>, 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: ObserverType>(_ 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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType, O6: ObservableType, O7: ObservableType, O8: ObservableType>
(_ 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<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: 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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType, O6: ObservableType, O7: ObservableType, O8: ObservableType>
(_ 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_<E1, E2, E3, E4, E5, E6, E7, E8, Observer: ObserverType> : CombineLatestSink<Observer> {
typealias Result = Observer.Element
typealias Parent = CombineLatest8<E1, E2, E3, E4, E5, E6, E7, E8, Result>
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 {
return try self._parent._resultSelector(self._latestElement1, self._latestElement2, self._latestElement3, self._latestElement4, self._latestElement5, self._latestElement6, self._latestElement7, self._latestElement8)
}
}
final class CombineLatest8<E1, E2, E3, E4, E5, E6, E7, E8, Result> : Producer<Result> {
typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws-> Result
let _source1: Observable<E1>
let _source2: Observable<E2>
let _source3: Observable<E3>
let _source4: Observable<E4>
let _source5: Observable<E5>
let _source6: Observable<E6>
let _source7: Observable<E7>
let _source8: Observable<E8>
let _resultSelector: ResultSelector
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, source4: Observable<E4>, source5: Observable<E5>, source6: Observable<E6>, source7: Observable<E7>, source8: Observable<E8>, 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: ObserverType>(_ 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)
}
}
//
// CombineLatest.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
protocol CombineLatestProtocol : class {
func next(_ index: Int)
func fail(_ error: Swift.Error)
func done(_ index: Int)
}
class CombineLatestSink<Observer: ObserverType>
: Sink<Observer>
, 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<Element>
: 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<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
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)
}
}
}
//
// 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.
Equivalent to:
func compactMap<Result>(_ transform: @escaping (Self.E) throws -> Result?) -> RxSwift.Observable<Result> {
return self.map { try? transform($0) }.filter { $0 != nil }.map { $0! }
}
- 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<Result>(_ transform: @escaping (Element) throws -> Result?)
-> Observable<Result> {
return CompactMap(source: self.asObservable(), transform: transform)
}
}
final private class CompactMapSink<SourceType, Observer: ObserverType>: Sink<Observer>, 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<SourceType>) {
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<SourceType, ResultType>: Producer<ResultType> {
typealias Transform = (SourceType) throws -> ResultType?
private let _source: Observable<SourceType>
private let _transform: Transform
init(source: Observable<SourceType>, transform: @escaping Transform) {
self._source = source
self._transform = transform
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// Completable+AndThen.swift
// RxSwift
//
// Created by Krunoslav Zaher on 7/2/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
extension PrimitiveSequenceType where Trait == CompletableTrait, Element == Never {
/**
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 andThen<Element>(_ second: Single<Element>) -> Single<Element> {
let completable = self.primitiveSequence.asObservable()
return Single(raw: ConcatCompletable(completable: completable, second: second.asObservable()))
}
/**
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 andThen<Element>(_ second: Maybe<Element>) -> Maybe<Element> {
let completable = self.primitiveSequence.asObservable()
return Maybe(raw: ConcatCompletable(completable: completable, second: second.asObservable()))
}
/**
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 andThen(_ second: Completable) -> Completable {
let completable = self.primitiveSequence.asObservable()
return Completable(raw: ConcatCompletable(completable: completable, second: second.asObservable()))
}
/**
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 andThen<Element>(_ second: Observable<Element>) -> Observable<Element> {
let completable = self.primitiveSequence.asObservable()
return ConcatCompletable(completable: completable, second: second.asObservable())
}
}
final private class ConcatCompletable<Element>: Producer<Element> {
fileprivate let _completable: Observable<Never>
fileprivate let _second: Observable<Element>
init(completable: Observable<Never>, second: Observable<Element>) {
self._completable = completable
self._second = second
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = ConcatCompletableSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
final private class ConcatCompletableSink<Observer: ObserverType>
: Sink<Observer>
, ObserverType {
typealias Element = Never
typealias Parent = ConcatCompletable<Observer.Element>
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 on(_ event: Event<Element>) {
switch event {
case .error(let error):
self.forwardOn(.error(error))
self.dispose()
case .next:
break
case .completed:
let otherSink = ConcatCompletableSinkOther(parent: self)
self._subscription.disposable = self._parent._second.subscribe(otherSink)
}
}
func run() -> Disposable {
let subscription = SingleAssignmentDisposable()
self._subscription.disposable = subscription
subscription.setDisposable(self._parent._completable.subscribe(self))
return self._subscription
}
}
final private class ConcatCompletableSinkOther<Observer: ObserverType>
: ObserverType {
typealias Element = Observer.Element
typealias Parent = ConcatCompletableSink<Observer>
private let _parent: Parent
init(parent: Parent) {
self._parent = parent
}
func on(_ event: Event<Observer.Element>) {
self._parent.forwardOn(event)
if event.isStopEvent {
self._parent.dispose()
}
}
}
//
// Completable.swift
// RxSwift
//
// Created by sergdort on 19/08/2017.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
#if DEBUG
import Foundation
#endif
/// Sequence containing 0 elements
public enum CompletableTrait { }
/// Represents a push style sequence containing 0 elements.
public typealias Completable = PrimitiveSequence<CompletableTrait, Swift.Never>
public enum CompletableEvent {
/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)
case error(Swift.Error)
/// Sequence completed successfully.
case completed
}
extension PrimitiveSequenceType where Trait == CompletableTrait, Element == Swift.Never {
public typealias CompletableObserver = (CompletableEvent) -> Void
/**
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 (@escaping CompletableObserver) -> Disposable) -> PrimitiveSequence<Trait, Element> {
let source = Observable<Element>.create { observer in
return subscribe { event in
switch event {
case .error(let error):
observer.on(.error(error))
case .completed:
observer.on(.completed)
}
}
}
return PrimitiveSequence(raw: source)
}
/**
Subscribes `observer` to receive events for this sequence.
- returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources.
*/
public func subscribe(_ observer: @escaping (CompletableEvent) -> Void) -> Disposable {
var stopped = false
return self.primitiveSequence.asObservable().subscribe { event in
if stopped { return }
stopped = true
switch event {
case .next:
rxFatalError("Completables can't emit values")
case .error(let error):
observer(.error(error))
case .completed:
observer(.completed)
}
}
}
/**
Subscribes a completion handler and an error handler for this sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onCompleted: (() -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil) -> Disposable {
#if DEBUG
let callStack = Hooks.recordCallStackOnError ? Thread.callStackSymbols : []
#else
let callStack = [String]()
#endif
return self.primitiveSequence.subscribe { event in
switch event {
case .error(let error):
if let onError = onError {
onError(error)
} else {
Hooks.defaultErrorHandler(callStack, error)
}
case .completed:
onCompleted?()
}
}
}
}
extension PrimitiveSequenceType where Trait == CompletableTrait, Element == Swift.Never {
/**
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) -> Completable {
return PrimitiveSequence(raw: Observable.error(error))
}
/**
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() -> Completable {
return PrimitiveSequence(raw: Observable.never())
}
/**
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() -> Completable {
return Completable(raw: Observable.empty())
}
}
extension PrimitiveSequenceType where Trait == CompletableTrait, Element == Swift.Never {
/**
Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter 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`(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)
-> Completable {
return Completable(raw: self.primitiveSequence.source.do(
onError: onError,
afterError: afterError,
onCompleted: onCompleted,
afterCompleted: afterCompleted,
onSubscribe: onSubscribe,
onSubscribed: onSubscribed,
onDispose: onDispose)
)
}
/**
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: Completable) -> Completable {
return Completable.concat(self.primitiveSequence, second)
}
/**
Concatenates all observable sequences in the given sequence, 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 given sequence, in sequential order.
*/
public static func concat<Sequence: Swift.Sequence>(_ sequence: Sequence) -> Completable
where Sequence.Element == Completable {
let source = Observable.concat(sequence.lazy.map { $0.asObservable() })
return Completable(raw: source)
}
/**
Concatenates all observable sequences in the given sequence, 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 given sequence, in sequential order.
*/
public static func concat<Collection: Swift.Collection>(_ collection: Collection) -> Completable
where Collection.Element == Completable {
let source = Observable.concat(collection.map { $0.asObservable() })
return Completable(raw: source)
}
/**
Concatenates all observable sequences in the given sequence, 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 given sequence, in sequential order.
*/
public static func concat(_ sources: Completable ...) -> Completable {
let source = Observable.concat(sources.map { $0.asObservable() })
return Completable(raw: source)
}
/**
Merges the completion of all Completables from a collection into a single Completable.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- note: For `Completable`, `zip` is an alias for `merge`.
- parameter sources: Collection of Completables to merge.
- returns: A Completable that merges the completion of all Completables.
*/
public static func zip<Collection: Swift.Collection>(_ sources: Collection) -> Completable
where Collection.Element == Completable {
let source = Observable.merge(sources.map { $0.asObservable() })
return Completable(raw: source)
}
/**
Merges the completion of all Completables from an array into a single Completable.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- note: For `Completable`, `zip` is an alias for `merge`.
- parameter sources: Array of observable sequences to merge.
- returns: A Completable that merges the completion of all Completables.
*/
public static func zip(_ sources: [Completable]) -> Completable {
let source = Observable.merge(sources.map { $0.asObservable() })
return Completable(raw: source)
}
/**
Merges the completion of all Completables into a single Completable.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- note: For `Completable`, `zip` is an alias for `merge`.
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func zip(_ sources: Completable...) -> Completable {
let source = Observable.merge(sources.map { $0.asObservable() })
return Completable(raw: source)
}
}
//
// 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<Disposable>? = Bag()
public var isDisposed: Bool {
self._lock.lock(); defer { self._lock.unlock() }
return 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.lock(); defer { self._lock.unlock() }
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.lock(); defer { self._lock.unlock() }
return 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.lock(); defer { self._lock.unlock() }
return 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<Disposable>? {
self._lock.lock(); defer { self._lock.unlock() }
let disposeBag = self._disposables
self._disposables = nil
return disposeBag
}
}
extension Disposables {
/// Creates a disposable with the given disposables.
public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) -> Cancelable {
return 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)
}
}
}
//
// 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<Source: ObservableConvertibleType>(_ second: Source) -> Observable<Element> where Source.Element == Element {
return 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: Swift.Sequence>(_ sequence: Sequence) -> Observable<Element>
where Sequence.Element == Observable<Element> {
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: Swift.Collection>(_ collection: Collection) -> Observable<Element>
where Collection.Element == Observable<Element> {
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<Element> ...) -> Observable<Element> {
return Concat(sources: sources, count: Int64(sources.count))
}
}
final private class ConcatSink<Sequence: Swift.Sequence, Observer: ObserverType>
: TailRecursiveSink<Sequence, Observer>
, 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<Element>){
switch event {
case .next:
self.forwardOn(event)
case .error:
self.forwardOn(event)
self.dispose()
case .completed:
self.schedule(.moveNext)
}
}
override func subscribeToNext(_ source: Observable<Element>) -> Disposable {
return source.subscribe(self)
}
override func extract(_ observable: Observable<Element>) -> SequenceGenerator? {
if let source = observable as? Concat<Sequence> {
return (source._sources.makeIterator(), source._count)
}
else {
return nil
}
}
}
final private class Concat<Sequence: Swift.Sequence>: Producer<Sequence.Element.Element> 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: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = ConcatSink<Sequence, Observer>(observer: observer, cancel: cancel)
let subscription = sink.run((self._sources.makeIterator(), self._count))
return (sink: sink, subscription: subscription)
}
}
//
// ConcurrentDispatchQueueScheduler.swift
// RxSwift
//
// Created by Krunoslav Zaher on 7/5/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import struct Foundation.Date
import struct Foundation.TimeInterval
import Dispatch
/// 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 {
return 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.
@available(iOS 8, OSX 10.10, *)
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<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
return 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<StateType>(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable {
return 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<StateType>(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable {
return self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action)
}
}
//
// ConcurrentMainScheduler.swift
// RxSwift
//
// Created by Krunoslav Zaher on 10/17/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import struct Foundation.Date
import struct Foundation.TimeInterval
import Dispatch
/**
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 {
return 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<StateType>(_ 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<StateType>(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable {
return 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<StateType>(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable {
return self._mainScheduler.schedulePeriodic(state, startAfter: startAfter, period: period, action: action)
}
}
//
// 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
}
//
// 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<Element>) -> Disposable) -> Observable<Element> {
return AnonymousObservable(subscribe)
}
}
final private class AnonymousObservableSink<Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias Element = Observer.Element
typealias Parent = AnonymousObservable<Element>
// 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<Element>) {
#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 {
return parent._subscribeHandler(AnyObserver(self))
}
}
final private class AnonymousObservable<Element>: Producer<Element> {
typealias SubscribeHandler = (AnyObserver<Element>) -> Disposable
let _subscribeHandler: SubscribeHandler
init(_ subscribeHandler: @escaping SubscribeHandler) {
self._subscribeHandler = subscribeHandler
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// CurrentThreadScheduler.swift
// RxSwift
//
// Created by Krunoslav Zaher on 8/30/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import class Foundation.NSObject
import protocol Foundation.NSCopying
import class Foundation.Thread
import Dispatch
#if os(Linux)
import struct Foundation.pthread_key_t
import func Foundation.pthread_setspecific
import func Foundation.pthread_getspecific
import func Foundation.pthread_key_create
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<Queue<ScheduledItemType>>
/// 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<pthread_key_t>.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<Int>.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<StateType>(_ 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<Queue<ScheduledItemType>>
if let existingQueue = existingQueue {
queue = existingQueue
}
else {
queue = RxMutableBox(Queue<ScheduledItemType>(capacity: 1))
CurrentThreadScheduler.queue = queue
}
let scheduledItem = ScheduledItem(action: action, state: state)
queue.value.enqueue(scheduledItem)
return scheduledItem
}
}
//
// Date+Dispatch.swift
// RxSwift
//
// Created by Krunoslav Zaher on 4/14/19.
// Copyright © 2019 Krunoslav Zaher. All rights reserved.
//
import struct Foundation.Date
import struct Foundation.TimeInterval
import enum Dispatch.DispatchTimeInterval
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()
}
}
}
//
// 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<Element> {
return Debounce(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
}
final private class DebounceSink<Observer: ObserverType>
: Sink<Observer>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = Observer.Element
typealias ParentType = Debounce<Element>
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<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
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.lock(); defer { self._lock.unlock() } // {
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<Element>: Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _dueTime: RxTimeInterval
fileprivate let _scheduler: SchedulerType
init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) {
self._source = source
self._dueTime = dueTime
self._scheduler = scheduler
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// Debug.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import struct Foundation.Date
import class Foundation.DateFormatter
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<Element> {
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<Source: ObservableType, Observer: ObserverType>: Sink<Observer>, ObserverType where Observer.Element == Source.Element {
typealias Element = Observer.Element
typealias Parent = Debug<Source>
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<Element>) {
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.disposed {
logEvent(self._parent._identifier, dateFormat: self._timestampFormatter, content: "isDisposed")
}
super.dispose()
}
}
final private class Debug<Source: ObservableType>: Producer<Source.Element> {
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: ObserverType>(_ 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)
}
}
//
// 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<Element> {
return DefaultIfEmpty(source: self.asObservable(), default: `default`)
}
}
final private class DefaultIfEmptySink<Observer: ObserverType>: Sink<Observer>, 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<Element>) {
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<SourceType>: Producer<SourceType> {
private let _source: Observable<SourceType>
private let _default: SourceType
init(source: Observable<SourceType>, `default`: SourceType) {
self._source = source
self._default = `default`
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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<Element>)
-> Observable<Element> {
return Deferred(observableFactory: observableFactory)
}
}
final private class DeferredSink<Source: ObservableType, Observer: ObserverType>: Sink<Observer>, 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<Element>) {
self.forwardOn(event)
switch event {
case .next:
break
case .error:
self.dispose()
case .completed:
self.dispose()
}
}
}
final private class Deferred<Source: ObservableType>: Producer<Source.Element> {
typealias Factory = () throws -> Source
private let _observableFactory : Factory
init(observableFactory: @escaping Factory) {
self._observableFactory = observableFactory
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// Delay.swift
// RxSwift
//
// Created by tarunon on 2016/02/09.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import struct Foundation.Date
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<Element> {
return Delay(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
}
final private class DelaySink<Observer: ObserverType>
: Sink<Observer>
, ObserverType {
typealias Element = Observer.Element
typealias Source = Observable<Element>
typealias DisposeKey = Bag<Disposable>.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<Element>?
// state
private var _queue = Queue<(eventTime: RxTime, event: Event<Element>)>(capacity: 0)
private var _disposed = false
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<Element>) {
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<Element>) -> Disposable {
self._sourceSubscription.setDisposable(source.subscribe(self))
return Disposables.create(_sourceSubscription, _cancelable)
}
}
final private class Delay<Element>: Producer<Element> {
private let _source: Observable<Element>
private let _dueTime: RxTimeInterval
private let _scheduler: SchedulerType
init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) {
self._source = source
self._dueTime = dueTime
self._scheduler = scheduler
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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<Element> {
return DelaySubscription(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
}
final private class DelaySubscriptionSink<Observer: ObserverType>
: Sink<Observer>, ObserverType {
typealias Element = Observer.Element
func on(_ event: Event<Element>) {
self.forwardOn(event)
if event.isStopEvent {
self.dispose()
}
}
}
final private class DelaySubscription<Element>: Producer<Element> {
private let _source: Observable<Element>
private let _dueTime: RxTimeInterval
private let _scheduler: SchedulerType
init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) {
self._source = source
self._dueTime = dueTime
self._scheduler = scheduler
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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<Element.Element> {
return Dematerialize(source: self.asObservable())
}
}
private final class DematerializeSink<T: EventConvertible, Observer: ObserverType>: Sink<Observer>, ObserverType where Observer.Element == T.Element {
fileprivate func on(_ event: Event<T>) {
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<T: EventConvertible>: Producer<T.Element> {
private let _source: Observable<T>
init(source: Observable<T>) {
self._source = source
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == T.Element {
let sink = DematerializeSink<T, Observer>(observer: observer, cancel: cancel)
let subscription = self._source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
//
// Deprecated.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/5/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
import Foundation
extension Observable {
/**
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.
*/
@available(*, deprecated, message: "Implicit conversions from any type to optional type are allowed and that is causing issues with `from` operator overloading.", renamed: "from(optional:)")
public static func from(_ optional: Element?) -> Observable<Element> {
return Observable.from(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.
*/
@available(*, deprecated, message: "Implicit conversions from any type to optional type are allowed and that is causing issues with `from` operator overloading.", renamed: "from(optional:scheduler:)")
public static func from(_ optional: Element?, scheduler: ImmediateSchedulerType) -> Observable<Element> {
return Observable.from(optional: optional, scheduler: scheduler)
}
}
extension ObservableType {
/**
Projects each element of an observable sequence into a new form by incorporating the element's index.
- seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html)
- parameter selector: A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
@available(*, deprecated, message: "Please use enumerated().map()")
public func mapWithIndex<Result>(_ selector: @escaping (Element, Int) throws -> Result)
-> Observable<Result> {
return self.enumerated().map { try selector($0.element, $0.index) }
}
/**
Projects each element of an observable sequence to an observable sequence by incorporating the element's index 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; the second parameter of the function represents the index of the source 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.
*/
@available(*, deprecated, message: "Please use enumerated().flatMap()")
public func flatMapWithIndex<Source: ObservableConvertibleType>(_ selector: @escaping (Element, Int) throws -> Source)
-> Observable<Source.Element> {
return self.enumerated().flatMap { try selector($0.element, $0.index) }
}
/**
Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
The element's index is used in the logic of the predicate function.
- seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html)
- parameter predicate: A function to test each element for a condition; the second parameter of the function represents the index of the source element.
- 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, message: "Please use enumerated().skipWhile().map()")
public func skipWhileWithIndex(_ predicate: @escaping (Element, Int) throws -> Bool) -> Observable<Element> {
return self.enumerated().skipWhile { try predicate($0.element, $0.index) }.map { $0.element }
}
/**
Returns elements from an observable sequence as long as a specified condition is true.
The element's index is used in the logic of the predicate function.
- seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html)
- parameter predicate: A function to test each element for a condition; the second parameter of the function represents the index of the source element.
- 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, message: "Please use enumerated().takeWhile().map()")
public func takeWhileWithIndex(_ predicate: @escaping (Element, Int) throws -> Bool) -> Observable<Element> {
return self.enumerated().takeWhile { try predicate($0.element, $0.index) }.map { $0.element }
}
}
extension Disposable {
/// Deprecated in favor of `disposed(by:)`
///
///
/// Adds `self` to `bag`.
///
/// - parameter bag: `DisposeBag` to add `self` to.
@available(*, deprecated, message: "use disposed(by:) instead", renamed: "disposed(by:)")
public func addDisposableTo(_ bag: DisposeBag) {
self.disposed(by: bag)
}
}
extension ObservableType {
/**
Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays latest element in buffer.
This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
- 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.
*/
@available(*, deprecated, message: "use share(replay: 1) instead", renamed: "share(replay:)")
public func shareReplayLatestWhileConnected()
-> Observable<Element> {
return self.share(replay: 1, scope: .whileConnected)
}
}
extension ObservableType {
/**
Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays maximum number of elements in buffer.
This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
- seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html)
- parameter bufferSize: Maximum element count of the replay buffer.
- returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
@available(*, deprecated, message: "Suggested replacement is `share(replay: 1)`. In case old 3.x behavior of `shareReplay` is required please use `share(replay: 1, scope: .forever)` instead.", renamed: "share(replay:)")
public func shareReplay(_ bufferSize: Int)
-> Observable<Element> {
return self.share(replay: bufferSize, scope: .forever)
}
}
/// Variable is a wrapper for `BehaviorSubject`.
///
/// Unlike `BehaviorSubject` it can't terminate with error, and when variable is deallocated
/// it will complete its observable sequence (`asObservable`).
///
/// **This concept will be deprecated from RxSwift but offical migration path hasn't been decided yet.**
/// https://github.com/ReactiveX/RxSwift/issues/1501
///
/// Current recommended replacement for this API is `RxCocoa.BehaviorRelay` because:
/// * `Variable` isn't a standard cross platform concept, hence it's out of place in RxSwift target.
/// * It doesn't have a counterpart for handling events (`PublishRelay`). It models state only.
/// * It doesn't have a consistent naming with *Relay or other Rx concepts.
/// * It has an inconsistent memory management model compared to other parts of RxSwift (completes on `deinit`).
///
/// Once plans are finalized, official availability attribute will be added in one of upcoming versions.
@available(*, deprecated, message: "Variable is deprecated. Please use `BehaviorRelay` as a replacement.")
public final class Variable<Element> {
private let _subject: BehaviorSubject<Element>
private var _lock = SpinLock()
// state
private var _value: Element
#if DEBUG
private let _synchronizationTracker = SynchronizationTracker()
#endif
/// Gets or sets current value of variable.
///
/// Whenever a new value is set, all the observers are notified of the change.
///
/// Even if the newly set value is same as the old value, observers are still notified for change.
public var value: Element {
get {
self._lock.lock(); defer { self._lock.unlock() }
return self._value
}
set(newValue) {
#if DEBUG
self._synchronizationTracker.register(synchronizationErrorMessage: .variable)
defer { self._synchronizationTracker.unregister() }
#endif
self._lock.lock()
self._value = newValue
self._lock.unlock()
self._subject.on(.next(newValue))
}
}
/// Initializes variable with initial value.
///
/// - parameter value: Initial variable value.
public init(_ value: Element) {
self._value = value
self._subject = BehaviorSubject(value: value)
}
/// - returns: Canonical interface for push style sequence
public func asObservable() -> Observable<Element> {
return self._subject
}
deinit {
self._subject.on(.completed)
}
}
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.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "delay(_:scheduler:)")
public func delay(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType)
-> Observable<Element> {
return self.delay(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler)
}
}
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.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timeout(_:scheduler:)")
public func timeout(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType)
-> Observable<Element> {
return timeout(.milliseconds(Int(dueTime * 1000.0)), 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.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timeout(_:other:scheduler:)")
public func timeout<OtherSource: ObservableConvertibleType>(_ dueTime: Foundation.TimeInterval, other: OtherSource, scheduler: SchedulerType)
-> Observable<Element> where Element == OtherSource.Element {
return timeout(.milliseconds(Int(dueTime * 1000.0)), other: other, scheduler: scheduler)
}
}
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.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "skip(_:scheduler:)")
public func skip(_ duration: Foundation.TimeInterval, scheduler: SchedulerType)
-> Observable<Element> {
return skip(.milliseconds(Int(duration * 1000.0)), scheduler: scheduler)
}
}
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.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "interval(_:scheduler:)")
public static func interval(_ period: Foundation.TimeInterval, scheduler: SchedulerType)
-> Observable<Element> {
return interval(.milliseconds(Int(period * 1000.0)), 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.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timer(_:period:scheduler:)")
public static func timer(_ dueTime: Foundation.TimeInterval, period: Foundation.TimeInterval? = nil, scheduler: SchedulerType)
-> Observable<Element> {
return timer(.milliseconds(Int(dueTime * 1000.0)), period: period.map { .milliseconds(Int($0 * 1000.0)) }, scheduler: scheduler)
}
}
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.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "throttle(_:latest:scheduler:)")
public func throttle(_ dueTime: Foundation.TimeInterval, latest: Bool = true, scheduler: SchedulerType)
-> Observable<Element> {
return throttle(.milliseconds(Int(dueTime * 1000.0)), latest: latest, scheduler: scheduler)
}
}
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.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "take(_:scheduler:)")
public func take(_ duration: Foundation.TimeInterval, scheduler: SchedulerType)
-> Observable<Element> {
return take(.milliseconds(Int(duration * 1000.0)), scheduler: scheduler)
}
}
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.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "delaySubscription(_:scheduler:)")
public func delaySubscription(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType)
-> Observable<Element> {
return delaySubscription(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler)
}
}
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`).
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "window(_:)")
public func window(timeSpan: Foundation.TimeInterval, count: Int, scheduler: SchedulerType)
-> Observable<Observable<Element>> {
return window(timeSpan: .milliseconds(Int(timeSpan * 1000.0)), count: count, scheduler: scheduler)
}
}
extension PrimitiveSequence {
/**
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.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "delay(_:scheduler:)")
public func delay(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return delay(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler)
}
/**
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.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "delaySubscription(_:scheduler:)")
public func delaySubscription(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return delaySubscription(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler)
}
/**
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.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timeout(_:scheduler:)")
public func timeout(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return timeout(.milliseconds(Int(dueTime * 1000.0)), 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.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timeout(_:other:scheduler:)")
public func timeout(_ dueTime: Foundation.TimeInterval,
other: PrimitiveSequence<Trait, Element>,
scheduler: SchedulerType) -> PrimitiveSequence<Trait, Element> {
return timeout(.milliseconds(Int(dueTime * 1000.0)), other: other, scheduler: scheduler)
}
}
extension PrimitiveSequenceType where Trait == SingleTrait {
/**
Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter 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.
*/
@available(*, deprecated, renamed: "do(onSuccess:onError:onSubscribe:onSubscribed:onDispose:)")
public func `do`(onNext: ((Element) throws -> Void)?,
onError: ((Swift.Error) throws -> Void)? = nil,
onSubscribe: (() -> Void)? = nil,
onSubscribed: (() -> Void)? = nil,
onDispose: (() -> Void)? = nil)
-> Single<Element> {
return self.`do`(
onSuccess: onNext,
onError: onError,
onSubscribe: onSubscribe,
onSubscribed: onSubscribed,
onDispose: onDispose
)
}
}
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.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "buffer(timeSpan:count:scheduler:)")
public func buffer(timeSpan: Foundation.TimeInterval, count: Int, scheduler: SchedulerType)
-> Observable<[Element]> {
return buffer(timeSpan: .milliseconds(Int(timeSpan * 1000.0)), count: count, scheduler: scheduler)
}
}
extension PrimitiveSequenceType 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 scheduler: Scheduler to run timers on.
- returns: An observable sequence that produces a value after due time has elapsed and then each period.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timer(_:scheduler:)")
public static func timer(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return timer(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler)
}
}
extension Completable {
/**
Merges the completion of all Completables from a collection into a single Completable.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of Completables to merge.
- returns: A Completable that merges the completion of all Completables.
*/
@available(*, deprecated, message: "Use Completable.zip instead.", renamed: "zip")
public static func merge<Collection: Swift.Collection>(_ sources: Collection) -> Completable
where Collection.Element == Completable {
return zip(sources)
}
/**
Merges the completion of all Completables from an array into a single Completable.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Array of observable sequences to merge.
- returns: A Completable that merges the completion of all Completables.
*/
@available(*, deprecated, message: "Use Completable.zip instead.", renamed: "zip")
public static func merge(_ sources: [Completable]) -> Completable {
return zip(sources)
}
/**
Merges the completion of all Completables into a single Completable.
- 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.
*/
@available(*, deprecated, message: "Use Completable.zip instead.", renamed: "zip")
public static func merge(_ sources: Completable...) -> Completable {
return zip(sources)
}
}
//
// 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 {
return DispatchQueue.getSpecific(key: token) != nil
}
}
//
// DispatchQueueConfiguration.swift
// RxSwift
//
// Created by Krunoslav Zaher on 7/23/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import Dispatch
import struct Foundation.TimeInterval
struct DispatchQueueConfiguration {
let queue: DispatchQueue
let leeway: DispatchTimeInterval
}
extension DispatchQueueConfiguration {
func schedule<StateType>(_ 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<StateType>(_ 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 conceputal 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<StateType>(_ 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 conceputal 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
}
}
//
// 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()
}
//
// 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() {}
}
//
// 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.lock(); defer { self._lock.unlock() }
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.lock(); defer { self._lock.unlock() }
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 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 an array of disposables to be gathered for disposal.
public func insert(_ disposables: [Disposable]) {
self._lock.lock(); defer { self._lock.unlock() }
if self._isDisposed {
disposables.forEach { $0.dispose() }
} else {
self._disposables += disposables
}
}
}
//
// 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
}
}
//
// 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<Element> {
return 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<Key: Equatable>(_ keySelector: @escaping (Element) throws -> Key)
-> Observable<Element> {
return 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<Element> {
return 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<K>(_ keySelector: @escaping (Element) throws -> K, comparer: @escaping (K, K) throws -> Bool)
-> Observable<Element> {
return DistinctUntilChanged(source: self.asObservable(), selector: keySelector, comparer: comparer)
}
}
final private class DistinctUntilChangedSink<Observer: ObserverType, Key>: Sink<Observer>, ObserverType {
typealias Element = Observer.Element
private let _parent: DistinctUntilChanged<Element, Key>
private var _currentKey: Key?
init(parent: DistinctUntilChanged<Element, Key>, observer: Observer, cancel: Cancelable) {
self._parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
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<Element, Key>: Producer<Element> {
typealias KeySelector = (Element) throws -> Key
typealias EqualityComparer = (Key, Key) throws -> Bool
private let _source: Observable<Element>
fileprivate let _selector: KeySelector
fileprivate let _comparer: EqualityComparer
init(source: Observable<Element>, selector: @escaping KeySelector, comparer: @escaping EqualityComparer) {
self._source = source
self._selector = selector
self._comparer = comparer
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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<Element> {
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<Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias Element = Observer.Element
typealias EventHandler = (Event<Element>) throws -> Void
typealias AfterEventHandler = (Event<Element>) 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<Element>) {
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<Element>: Producer<Element> {
typealias EventHandler = (Event<Element>) throws -> Void
typealias AfterEventHandler = (Event<Element>) throws -> Void
private let _source: Observable<Element>
private let _eventHandler: EventHandler
private let _afterEventHandler: AfterEventHandler
private let _onSubscribe: (() -> Void)?
private let _onSubscribed: (() -> Void)?
private let _onDispose: (() -> Void)?
init(source: Observable<Element>, 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: ObserverType>(_ 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)
}
}
//
// 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.
*/
public func elementAt(_ index: Int)
-> Observable<Element> {
return ElementAt(source: self.asObservable(), index: index, throwOnEmpty: true)
}
}
final private class ElementAtSink<Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias SourceType = Observer.Element
typealias Parent = ElementAt<SourceType>
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<SourceType>) {
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<SourceType>: Producer<SourceType> {
let _source: Observable<SourceType>
let _throwOnEmpty: Bool
let _index: Int
init(source: Observable<SourceType>, 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: ObserverType>(_ 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)
}
}
//
// 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<Element> {
return EmptyProducer<Element>()
}
}
final private class EmptyProducer<Element>: Producer<Element> {
override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
observer.on(.completed)
return Disposables.create()
}
}
//
// 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)> {
return Enumerated(source: self.asObservable())
}
}
final private class EnumeratedSink<Element, Observer: ObserverType>: Sink<Observer>, ObserverType where Observer.Element == (index: Int, element: Element) {
var index = 0
func on(_ event: Event<Element>) {
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<Element>: Producer<(index: Int, element: Element)> {
private let _source: Observable<Element>
init(source: Observable<Element>) {
self._source = source
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == (index: Int, element: Element) {
let sink = EnumeratedSink<Element, Observer>(observer: observer, cancel: cancel)
let subscription = self._source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
//
// 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<Element> {
return ErrorProducer(error: error)
}
}
final private class ErrorProducer<Element>: Producer<Element> {
private let _error: Swift.Error
init(error: Swift.Error) {
self._error = error
}
override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
observer.on(.error(self._error))
return Disposables.create()
}
}
//
// 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."
}
}
}
//
// 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)**
public enum Event<Element> {
/// 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<Result>(_ transform: (Element) throws -> Result) -> Event<Result> {
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<Element>`.
public protocol EventConvertible {
/// Type of element in event
associatedtype Element
@available(*, deprecated, renamed: "Element")
typealias ElementType = Element
/// Event representation of this instance
var event: Event<Element> { get }
}
extension Event: EventConvertible {
/// Event representation of this instance
public var event: Event<Element> {
return self
}
}
//
// 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<Element> {
return 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()
-> Completable {
return self.flatMap { _ in
return Observable<Never>.empty()
}
.asCompletable()
}
}
final private class FilterSink<Observer: ObserverType>: Sink<Observer>, 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<Element>) {
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<Element>: Producer<Element> {
typealias Predicate = (Element) throws -> Bool
private let _source: Observable<Element>
private let _predicate: Predicate
init(source: Observable<Element>, predicate: @escaping Predicate) {
self._source = source
self._predicate = predicate
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// First.swift
// RxSwift
//
// Created by Krunoslav Zaher on 7/31/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
private final class FirstSink<Element, Observer: ObserverType> : Sink<Observer>, ObserverType where Observer.Element == Element? {
typealias Parent = First<Element>
func on(_ event: Event<Element>) {
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<Element>: Producer<Element?> {
private let _source: Observable<Element>
init(source: Observable<Element>) {
self._source = source
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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<Element> {
return Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler)
}
}
final private class GenerateSink<Sequence, Observer: ObserverType>: Sink<Observer> {
typealias Parent = Generate<Sequence, Observer.Element>
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<Sequence, Element>: Producer<Element> {
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: ObserverType>(_ 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)
}
}
//
// 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<Key: Hashable>(keySelector: @escaping (Element) throws -> Key)
-> Observable<GroupedObservable<Key, Element>> {
return GroupBy(source: self.asObservable(), selector: keySelector)
}
}
final private class GroupedObservableImpl<Element>: Observable<Element> {
private var _subject: PublishSubject<Element>
private var _refCount: RefCountDisposable
init(subject: PublishSubject<Element>, refCount: RefCountDisposable) {
self._subject = subject
self._refCount = refCount
}
override public func subscribe<Observer: ObserverType>(_ 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<Key: Hashable, Element, Observer: ObserverType>
: Sink<Observer>
, ObserverType where Observer.Element == GroupedObservable<Key, Element> {
typealias ResultType = Observer.Element
typealias Parent = GroupBy<Key, Element>
private let _parent: Parent
private let _subscription = SingleAssignmentDisposable()
private var _refCountDisposable: RefCountDisposable!
private var _groupedSubjectTable: [Key: PublishSubject<Element>]
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self._parent = parent
self._groupedSubjectTable = [Key: PublishSubject<Element>]()
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<Element>()
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<Element>) {
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<Element>) {
for writer in self._groupedSubjectTable.values {
writer.on(event)
}
}
}
final private class GroupBy<Key: Hashable, Element>: Producer<GroupedObservable<Key,Element>> {
typealias KeySelector = (Element) throws -> Key
fileprivate let _source: Observable<Element>
fileprivate let _selector: KeySelector
init(source: Observable<Element>, selector: @escaping KeySelector) {
self._source = source
self._selector = selector
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == GroupedObservable<Key,Element> {
let sink = GroupBySink(parent: self, observer: observer, cancel: cancel)
return (sink: sink, subscription: sink.run())
}
}
//
// 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<Key, Element> : ObservableType {
/// Gets the common key.
public let key: Key
private let source: Observable<Element>
/// 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<Element>) {
self.key = key
self.source = source
}
/// Subscribes `observer` to receive events for this sequence.
public func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
return self.source.subscribe(observer)
}
/// Converts `self` to `Observable` sequence.
public func asObservable() -> Observable<Element> {
return self.source
}
}
//
// HistoricalScheduler.swift
// RxSwift
//
// Created by Krunoslav Zaher on 12/27/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import struct Foundation.Date
/// Provides a virtual time scheduler that uses `Date` for absolute time and `NSTimeInterval` for relative time.
public class HistoricalScheduler : VirtualTimeScheduler<HistoricalSchedulerTimeConverter> {
/**
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())
}
}
//
// 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 {
return 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 {
return 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 {
return 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 {
return 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 {
return 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
}
}
}
//
// 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<StateType>(_ 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: 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)
}
}
//
// 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<Element> : Sequence {
typealias Iterator = AnyIterator<Element>
private let _repeatedValue: Element
init(repeatedValue: Element) {
_repeatedValue = repeatedValue
}
func makeIterator() -> Iterator {
let repeatedValue = _repeatedValue
return AnyIterator {
return repeatedValue
}
}
}
//
// InvocableScheduledItem.swift
// RxSwift
//
// Created by Krunoslav Zaher on 11/7/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
struct InvocableScheduledItem<I: InvocableWithValueType> : 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)
}
}
//
// 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)
}
//
// 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<Element> {
return 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<Element> {
return JustScheduled(element: element, scheduler: scheduler)
}
}
final private class JustScheduledSink<Observer: ObserverType>: Sink<Observer> {
typealias Parent = JustScheduled<Observer.Element>
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<Element>: Producer<Element> {
fileprivate let _scheduler: ImmediateSchedulerType
fileprivate let _element: Element
init(element: Element, scheduler: ImmediateSchedulerType) {
self._scheduler = scheduler
self._element = element
}
override func run<Observer: ObserverType>(_ 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<Element>: Producer<Element> {
private let _element: Element
init(element: Element) {
self._element = element
}
override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
observer.on(.next(self._element))
observer.on(.completed)
return Disposables.create()
}
}
//
// 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: () -> Void) {
self.lock(); defer { self.unlock() }
action()
}
@inline(__always)
final func calculateLocked<T>(_ action: () -> T) -> T {
self.lock(); defer { self.unlock() }
return action()
}
@inline(__always)
final func calculateLockedOrFail<T>(_ action: () throws -> T) throws -> T {
self.lock(); defer { self.unlock() }
let result = try action()
return result
}
}
//
// LockOwnerType.swift
// RxSwift
//
// Created by Krunoslav Zaher on 10/25/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
protocol LockOwnerType : class, Lock {
var _lock: RecursiveLock { get }
}
extension LockOwnerType {
func lock() {
self._lock.lock()
}
func unlock() {
self._lock.unlock()
}
}
//
// 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 class 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 class 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<StateType>(_ 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 {
_ = action(state)
}
decrement(self.numberEnqueued)
}
return cancel
}
}
//
// 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<Result>(_ transform: @escaping (Element) throws -> Result)
-> Observable<Result> {
return Map(source: self.asObservable(), transform: transform)
}
}
final private class MapSink<SourceType, Observer: ObserverType>: Sink<Observer>, 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<SourceType>) {
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<SourceType, ResultType>: Producer<ResultType> {
typealias Transform = (SourceType) throws -> ResultType
private let _source: Observable<SourceType>
private let _transform: Transform
init(source: Observable<SourceType>, transform: @escaping Transform) {
self._source = source
self._transform = transform
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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<E>. The returned Observable never errors, but it does complete after observing all of the events of the underlying Observable.
*/
public func materialize() -> Observable<Event<Element>> {
return Materialize(source: self.asObservable())
}
}
private final class MaterializeSink<Element, Observer: ObserverType>: Sink<Observer>, ObserverType where Observer.Element == Event<Element> {
func on(_ event: Event<Element>) {
self.forwardOn(.next(event))
if event.isStopEvent {
self.forwardOn(.completed)
self.dispose()
}
}
}
final private class Materialize<T>: Producer<Event<T>> {
private let _source: Observable<T>
init(source: Observable<T>) {
self._source = source
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// Maybe.swift
// RxSwift
//
// Created by sergdort on 19/08/2017.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
#if DEBUG
import Foundation
#endif
/// Sequence containing 0 or 1 elements
public enum MaybeTrait { }
/// Represents a push style sequence containing 0 or 1 element.
public typealias Maybe<Element> = PrimitiveSequence<MaybeTrait, Element>
public enum MaybeEvent<Element> {
/// One and only sequence element is produced. (underlying observable sequence emits: `.next(Element)`, `.completed`)
case success(Element)
/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)
case error(Swift.Error)
/// Sequence completed successfully.
case completed
}
extension PrimitiveSequenceType where Trait == MaybeTrait {
public typealias MaybeObserver = (MaybeEvent<Element>) -> Void
/**
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 (@escaping MaybeObserver) -> Disposable) -> PrimitiveSequence<Trait, Element> {
let source = Observable<Element>.create { observer in
return subscribe { event in
switch event {
case .success(let element):
observer.on(.next(element))
observer.on(.completed)
case .error(let error):
observer.on(.error(error))
case .completed:
observer.on(.completed)
}
}
}
return PrimitiveSequence(raw: source)
}
/**
Subscribes `observer` to receive events for this sequence.
- returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources.
*/
public func subscribe(_ observer: @escaping (MaybeEvent<Element>) -> Void) -> Disposable {
var stopped = false
return self.primitiveSequence.asObservable().subscribe { event in
if stopped { return }
stopped = true
switch event {
case .next(let element):
observer(.success(element))
case .error(let error):
observer(.error(error))
case .completed:
observer(.completed)
}
}
}
/**
Subscribes a success handler, an error handler, and a completion handler for this sequence.
- parameter onSuccess: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onSuccess: ((Element) -> Void)? = nil,
onError: ((Swift.Error) -> Void)? = nil,
onCompleted: (() -> Void)? = nil) -> Disposable {
#if DEBUG
let callStack = Hooks.recordCallStackOnError ? Thread.callStackSymbols : []
#else
let callStack = [String]()
#endif
return self.primitiveSequence.subscribe { event in
switch event {
case .success(let element):
onSuccess?(element)
case .error(let error):
if let onError = onError {
onError(error)
} else {
Hooks.defaultErrorHandler(callStack, error)
}
case .completed:
onCompleted?()
}
}
}
}
extension PrimitiveSequenceType where Trait == MaybeTrait {
/**
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) -> Maybe<Element> {
return Maybe(raw: Observable.just(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) -> Maybe<Element> {
return Maybe(raw: Observable.just(element, scheduler: scheduler))
}
/**
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) -> Maybe<Element> {
return PrimitiveSequence(raw: Observable.error(error))
}
/**
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() -> Maybe<Element> {
return PrimitiveSequence(raw: Observable.never())
}
/**
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() -> Maybe<Element> {
return Maybe(raw: Observable.empty())
}
}
extension PrimitiveSequenceType where Trait == MaybeTrait {
/**
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)
-> Maybe<Element> {
return Maybe(raw: self.primitiveSequence.source.do(
onNext: onNext,
afterNext: afterNext,
onError: onError,
afterError: afterError,
onCompleted: onCompleted,
afterCompleted: afterCompleted,
onSubscribe: onSubscribe,
onSubscribed: onSubscribed,
onDispose: onDispose)
)
}
/**
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)
-> Maybe<Element> {
return Maybe(raw: self.primitiveSequence.source.filter(predicate))
}
/**
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<Result>(_ transform: @escaping (Element) throws -> Result)
-> Maybe<Result> {
return Maybe(raw: self.primitiveSequence.source.map(transform))
}
/**
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.
- returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source.
*/
public func compactMap<Result>(_ transform: @escaping (Element) throws -> Result?)
-> Maybe<Result> {
return Maybe(raw: self.primitiveSequence.source.compactMap(transform))
}
/**
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<Result>(_ selector: @escaping (Element) throws -> Maybe<Result>)
-> Maybe<Result> {
return Maybe<Result>(raw: self.primitiveSequence.source.flatMap(selector))
}
/**
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) -> Single<Element> {
return Single(raw: self.primitiveSequence.source.ifEmpty(default: `default`))
}
/**
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 switchTo: 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: Maybe<Element>) -> Maybe<Element> {
return Maybe(raw: self.primitiveSequence.source.ifEmpty(switchTo: other.primitiveSequence.source))
}
/**
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 switchTo: 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: Single<Element>) -> Single<Element> {
return Single(raw: self.primitiveSequence.source.ifEmpty(switchTo: other.primitiveSequence.source))
}
/**
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 catchErrorJustReturn(_ element: Element)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: self.primitiveSequence.source.catchErrorJustReturn(element))
}
}
//
// 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<Source: ObservableConvertibleType>(_ selector: @escaping (Element) throws -> Source)
-> Observable<Source.Element> {
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<Source: ObservableConvertibleType>(_ selector: @escaping (Element) throws -> Source)
-> Observable<Source.Element> {
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<Element.Element> {
return 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<Element.Element> {
return 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<Element.Element> {
return 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<Collection: Swift.Collection>(_ sources: Collection) -> Observable<Element> where Collection.Element == Observable<Element> {
return 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<Element>]) -> Observable<Element> {
return 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<Element>...) -> Observable<Element> {
return 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<Source: ObservableConvertibleType>(_ selector: @escaping (Element) throws -> Source)
-> Observable<Source.Element> {
return ConcatMap(source: self.asObservable(), selector: selector)
}
}
private final class MergeLimitedSinkIter<SourceElement, SourceSequence: ObservableConvertibleType, Observer: ObserverType>
: ObserverType
, LockOwnerType
, SynchronizedOnType where SourceSequence.Element == Observer.Element {
typealias Element = Observer.Element
typealias DisposeKey = CompositeDisposable.DisposeKey
typealias Parent = MergeLimitedSink<SourceElement, SourceSequence, Observer>
private let _parent: Parent
private let _disposeKey: DisposeKey
var _lock: RecursiveLock {
return self._parent._lock
}
init(parent: Parent, disposeKey: DisposeKey) {
self._parent = parent
self._disposeKey = disposeKey
}
func on(_ event: Event<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
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<SourceElement, SourceSequence: ObservableConvertibleType, Observer: ObserverType>: MergeLimitedSink<SourceElement, SourceSequence, Observer> 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 {
return try self._selector(element)
}
}
private final class MergeLimitedBasicSink<SourceSequence: ObservableConvertibleType, Observer: ObserverType>: MergeLimitedSink<SourceSequence, SourceSequence, Observer> where Observer.Element == SourceSequence.Element {
override func performMap(_ element: SourceSequence) throws -> SourceSequence {
return element
}
}
private class MergeLimitedSink<SourceElement, SourceSequence: ObservableConvertibleType, Observer: ObserverType>
: Sink<Observer>
, ObserverType where Observer.Element == SourceSequence.Element {
typealias QueueType = Queue<SourceSequence>
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<SourceElement>) -> 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.lock(); defer { self._lock.unlock() } // {
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<SourceElement>) {
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.lock(); defer { self._lock.unlock() }
self.forwardOn(.error(error))
self.dispose()
case .completed:
self._lock.lock(); defer { self._lock.unlock() }
if self._activeCount == 0 {
self.forwardOn(.completed)
self.dispose()
}
else {
self._sourceSubscription.dispose()
}
self._stopped = true
}
}
}
final private class MergeLimited<SourceSequence: ObservableConvertibleType>: Producer<SourceSequence.Element> {
private let _source: Observable<SourceSequence>
private let _maxConcurrent: Int
init(source: Observable<SourceSequence>, maxConcurrent: Int) {
self._source = source
self._maxConcurrent = maxConcurrent
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element {
let sink = MergeLimitedBasicSink<SourceSequence, Observer>(maxConcurrent: self._maxConcurrent, observer: observer, cancel: cancel)
let subscription = sink.run(self._source)
return (sink: sink, subscription: subscription)
}
}
// MARK: Merge
private final class MergeBasicSink<Source: ObservableConvertibleType, Observer: ObserverType> : MergeSink<Source, Source, Observer> where Observer.Element == Source.Element {
override func performMap(_ element: Source) throws -> Source {
return element
}
}
// MARK: flatMap
private final class FlatMapSink<SourceElement, SourceSequence: ObservableConvertibleType, Observer: ObserverType> : MergeSink<SourceElement, SourceSequence, Observer> 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 {
return try self._selector(element)
}
}
// MARK: FlatMapFirst
private final class FlatMapFirstSink<SourceElement, SourceSequence: ObservableConvertibleType, Observer: ObserverType> : MergeSink<SourceElement, SourceSequence, Observer> where Observer.Element == SourceSequence.Element {
typealias Selector = (SourceElement) throws -> SourceSequence
private let _selector: Selector
override var subscribeNext: Bool {
return 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 {
return try self._selector(element)
}
}
private final class MergeSinkIter<SourceElement, SourceSequence: ObservableConvertibleType, Observer: ObserverType> : ObserverType where Observer.Element == SourceSequence.Element {
typealias Parent = MergeSink<SourceElement, SourceSequence, Observer>
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<Element>) {
self._parent._lock.lock(); defer { self._parent._lock.unlock() } // lock {
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<SourceElement, SourceSequence: ObservableConvertibleType, Observer: ObserverType>
: Sink<Observer>
, ObserverType where Observer.Element == SourceSequence.Element {
typealias ResultType = Observer.Element
typealias Element = SourceElement
let _lock = RecursiveLock()
var subscribeNext: Bool {
return 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.lock(); defer { self._lock.unlock() } // {
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<SourceElement>) {
switch event {
case .next(let element):
if let value = self.nextElementArrived(element: element) {
self.subscribeInner(value.asObservable())
}
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._sourceSubscription.dispose()
self.checkCompleted()
}
}
func subscribeInner(_ source: Observable<Observer.Element>) {
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<Observer.Element>]) -> 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<SourceElement>) -> Disposable {
_ = self._group.insert(self._sourceSubscription)
let subscription = source.subscribe(self)
self._sourceSubscription.setDisposable(subscription)
return self._group
}
}
// MARK: Producers
final private class FlatMap<SourceElement, SourceSequence: ObservableConvertibleType>: Producer<SourceSequence.Element> {
typealias Selector = (SourceElement) throws -> SourceSequence
private let _source: Observable<SourceElement>
private let _selector: Selector
init(source: Observable<SourceElement>, selector: @escaping Selector) {
self._source = source
self._selector = selector
}
override func run<Observer: ObserverType>(_ 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<SourceElement, SourceSequence: ObservableConvertibleType>: Producer<SourceSequence.Element> {
typealias Selector = (SourceElement) throws -> SourceSequence
private let _source: Observable<SourceElement>
private let _selector: Selector
init(source: Observable<SourceElement>, selector: @escaping Selector) {
self._source = source
self._selector = selector
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element {
let sink = FlatMapFirstSink<SourceElement, SourceSequence, Observer>(selector: self._selector, observer: observer, cancel: cancel)
let subscription = sink.run(self._source)
return (sink: sink, subscription: subscription)
}
}
final class ConcatMap<SourceElement, SourceSequence: ObservableConvertibleType>: Producer<SourceSequence.Element> {
typealias Selector = (SourceElement) throws -> SourceSequence
private let _source: Observable<SourceElement>
private let _selector: Selector
init(source: Observable<SourceElement>, selector: @escaping Selector) {
self._source = source
self._selector = selector
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element {
let sink = ConcatMapSink<SourceElement, SourceSequence, Observer>(selector: self._selector, observer: observer, cancel: cancel)
let subscription = sink.run(self._source)
return (sink: sink, subscription: subscription)
}
}
final class Merge<SourceSequence: ObservableConvertibleType> : Producer<SourceSequence.Element> {
private let _source: Observable<SourceSequence>
init(source: Observable<SourceSequence>) {
self._source = source
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element {
let sink = MergeBasicSink<SourceSequence, Observer>(observer: observer, cancel: cancel)
let subscription = sink.run(self._source)
return (sink: sink, subscription: subscription)
}
}
final private class MergeArray<Element>: Producer<Element> {
private let _sources: [Observable<Element>]
init(sources: [Observable<Element>]) {
self._sources = sources
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = MergeBasicSink<Observable<Element>, Observer>(observer: observer, cancel: cancel)
let subscription = sink.run(self._sources)
return (sink: sink, subscription: subscription)
}
}
//
// 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<Element>
: Observable<Element>
, 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<Subject: SubjectType, Result>(_ subjectSelector: @escaping () throws -> Subject, selector: @escaping (Observable<Subject.Element>) throws -> Observable<Result>)
-> Observable<Result> 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<Element> {
return 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<Element> {
return 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<Element> {
return 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<Element> {
return 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: SubjectType>(_ subject: Subject)
-> ConnectableObservable<Subject.Element> where Subject.Observer.Element == Element {
return 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<Subject: SubjectType>(makeSubject: @escaping () -> Subject)
-> ConnectableObservable<Subject.Element> where Subject.Observer.Element == Element {
return ConnectableObservableAdapter(source: self.asObservable(), makeSubject: makeSubject)
}
}
final private class Connection<Subject: SubjectType>: ObserverType, Disposable {
typealias Element = Subject.Observer.Element
private var _lock: RecursiveLock
// state
private var _parent: ConnectableObservableAdapter<Subject>?
private var _subscription : Disposable?
private var _subjectObserver: Subject.Observer
private let _disposed = AtomicInt(0)
init(parent: ConnectableObservableAdapter<Subject>, subjectObserver: Subject.Observer, lock: RecursiveLock, subscription: Disposable) {
self._parent = parent
self._subscription = subscription
self._lock = lock
self._subjectObserver = subjectObserver
}
func on(_ event: Event<Subject.Observer.Element>) {
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 = _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<Subject: SubjectType>
: ConnectableObservable<Subject.Element> {
typealias ConnectionType = Connection<Subject>
private let _source: Observable<Subject.Observer.Element>
private let _makeSubject: () -> Subject
fileprivate let _lock = RecursiveLock()
fileprivate var _subject: Subject?
// state
fileprivate var _connection: ConnectionType?
init(source: Observable<Subject.Observer.Element>, makeSubject: @escaping () -> Subject) {
self._source = source
self._makeSubject = makeSubject
self._subject = nil
self._connection = nil
}
override func connect() -> Disposable {
return self._lock.calculateLocked {
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: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Subject.Element {
return self.lazySubject.subscribe(observer)
}
}
final private class RefCountSink<ConnectableSource: ConnectableObservableType, Observer: ObserverType>
: Sink<Observer>
, ObserverType where ConnectableSource.Element == Observer.Element {
typealias Element = Observer.Element
typealias Parent = RefCount<ConnectableSource>
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.disposed {
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<Element>) {
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<ConnectableSource: ConnectableObservableType>: Producer<ConnectableSource.Element> {
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: ObserverType>(_ 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<Subject: SubjectType, Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias Element = Observer.Element
typealias ResultType = Element
typealias MutlicastType = Multicast<Subject, Observer.Element>
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<ResultType>) {
self.forwardOn(event)
switch event {
case .next: break
case .error, .completed:
self.dispose()
}
}
}
final private class Multicast<Subject: SubjectType, Result>: Producer<Result> {
typealias SubjectSelectorType = () throws -> Subject
typealias SelectorType = (Observable<Subject.Element>) throws -> Observable<Result>
fileprivate let _source: Observable<Subject.Observer.Element>
fileprivate let _subjectSelector: SubjectSelectorType
fileprivate let _selector: SelectorType
init(source: Observable<Subject.Observer.Element>, subjectSelector: @escaping SubjectSelectorType, selector: @escaping SelectorType) {
self._source = source
self._subjectSelector = subjectSelector
self._selector = selector
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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<Element> {
return NeverProducer()
}
}
final private class NeverProducer<Element>: Producer<Element> {
override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
return Disposables.create()
}
}
//
// 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 {
return NopDisposable.noOp
}
}
//
// 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<Element> : ObservableType {
init() {
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
}
public func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
rxAbstractMethod()
}
public func asObservable() -> Observable<Element> {
return self
}
deinit {
#if TRACE_RESOURCES
_ = Resources.decrementTotal()
#endif
}
}
//
// 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<Element>`).
public protocol ObservableConvertibleType {
/// Type of elements in sequence.
associatedtype Element
@available(*, deprecated, renamed: "Element")
typealias E = Element
/// Converts `self` to `Observable` sequence.
///
/// - returns: Observable sequence that represents `self`.
func asObservable() -> Observable<Element>
}
//
// 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<Element>) -> 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.
- 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<Element> { 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 class Foundation.NSRecursiveLock
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.lock(); defer { _lock.unlock() }
return _defaultErrorHandler
}
set {
_lock.lock(); defer { _lock.unlock() }
_defaultErrorHandler = newValue
}
}
/// Subscription callstack block to fetch custom callstack information.
public static var customCaptureSubscriptionCallstack: CustomCaptureSubscriptionCallstack {
get {
_lock.lock(); defer { _lock.unlock() }
return _customCaptureSubscriptionCallstack
}
set {
_lock.lock(); defer { _lock.unlock() }
_customCaptureSubscriptionCallstack = newValue
}
}
}
//
// ObservableType+PrimitiveSequence.swift
// RxSwift
//
// Created by Krunoslav Zaher on 9/17/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
The `asSingle` operator 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 when the source Observable has completed, or throws an exception if more (or none) of them are emitted.
*/
public func asSingle() -> Single<Element> {
return PrimitiveSequence(raw: AsSingle(source: self.asObservable()))
}
/**
The `first` operator emits only the very first item emitted by this Observable,
or nil if this Observable completes without emitting anything.
- seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html)
- returns: An observable sequence that emits a single element or nil if the source observable sequence completes without emitting any items.
*/
public func first() -> Single<Element?> {
return PrimitiveSequence(raw: First(source: self.asObservable()))
}
/**
The `asMaybe` operator throws a `RxError.moreThanOneElement`
if the source Observable does not emit at most 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, completes when the source Observable has completed, or throws an exception if more of them are emitted.
*/
public func asMaybe() -> Maybe<Element> {
return PrimitiveSequence(raw: AsMaybe(source: self.asObservable()))
}
}
extension ObservableType where Element == Never {
/**
- returns: An observable sequence that completes.
*/
public func asCompletable()
-> Completable {
return PrimitiveSequence(raw: self.asObservable())
}
}
//
// 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: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element
}
extension ObservableType {
/// Default implementation of converting `ObservableType` to `Observable`.
public func asObservable() -> Observable<Element> {
// temporary workaround
//return Observable.create(subscribe: self.subscribe)
return Observable.create { o in
return self.subscribe(o)
}
}
}
//
// 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 observeOn(_ scheduler: ImmediateSchedulerType)
-> Observable<Element> {
if let scheduler = scheduler as? SerialDispatchQueueScheduler {
return ObserveOnSerialDispatchQueue(source: self.asObservable(), scheduler: scheduler)
}
else {
return ObserveOn(source: self.asObservable(), scheduler: scheduler)
}
}
}
final private class ObserveOn<Element>: Producer<Element> {
let scheduler: ImmediateSchedulerType
let source: Observable<Element>
init(source: Observable<Element>, scheduler: ImmediateSchedulerType) {
self.scheduler = scheduler
self.source = source
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
}
override func run<Observer: ObserverType>(_ 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<Observer: ObserverType>: ObserverBase<Observer.Element> {
typealias Element = Observer.Element
let _scheduler: ImmediateSchedulerType
var _lock = SpinLock()
let _observer: Observer
// state
var _state = ObserveOnState.stopped
var _queue = Queue<Event<Element>>(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<Element>) {
let shouldStart = self._lock.calculateLocked { () -> 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.calculateLocked { () -> (Event<Element>?, 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.lock(); defer { self._lock.unlock() } // {
if !self._queue.isEmpty {
return true
}
else {
self._state = .stopped
return false
}
// }
}
override func dispose() {
super.dispose()
self._cancel.dispose()
self._scheduleDisposable.dispose()
}
}
#if TRACE_RESOURCES
private let _numberOfSerialDispatchQueueObservables = AtomicInt(0)
extension Resources {
/**
Counts number of `SerialDispatchQueueObservables`.
Purposed for unit tests.
*/
public static var numberOfSerialDispatchQueueObservables: Int32 {
return load(_numberOfSerialDispatchQueueObservables)
}
}
#endif
final private class ObserveOnSerialDispatchQueueSink<Observer: ObserverType>: ObserverBase<Observer.Element> {
let scheduler: SerialDispatchQueueScheduler
let observer: Observer
let cancel: Cancelable
var cachedScheduleLambda: (((sink: ObserveOnSerialDispatchQueueSink<Observer>, event: Event<Element>)) -> 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<Element>) {
_ = self.scheduler.schedule((self, event), action: self.cachedScheduleLambda!)
}
override func dispose() {
super.dispose()
self.cancel.dispose()
}
}
final private class ObserveOnSerialDispatchQueue<Element>: Producer<Element> {
let scheduler: SerialDispatchQueueScheduler
let source: Observable<Element>
init(source: Observable<Element>, scheduler: SerialDispatchQueueScheduler) {
self.scheduler = scheduler
self.source = source
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
_ = increment(_numberOfSerialDispatchQueueObservables)
#endif
}
override func run<Observer: ObserverType>(_ 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(_numberOfSerialDispatchQueueObservables)
}
#endif
}
//
// ObserverBase.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
class ObserverBase<Element> : Disposable, ObserverType {
private let _isStopped = AtomicInt(0)
func on(_ event: Event<Element>) {
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<Element>) {
rxAbstractMethod()
}
func dispose() {
fetchOr(self._isStopped, 1)
}
}
//
// 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
@available(*, deprecated, renamed: "Element")
typealias E = Element
/// Notify observer about sequence event.
///
/// - parameter event: Event that occurred.
func on(_ event: Event<Element>)
}
/// 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))
}
}
//
// OperationQueueScheduler.swift
// RxSwift
//
// Created by Krunoslav Zaher on 4/4/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import class Foundation.Operation
import class Foundation.OperationQueue
import class Foundation.BlockOperation
import Dispatch
/// 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<StateType>(_ 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
}
}
//
// 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<Element> {
return 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<Element> {
return ObservableOptionalScheduled(optional: optional, scheduler: scheduler)
}
}
final private class ObservableOptionalScheduledSink<Observer: ObserverType>: Sink<Observer> {
typealias Element = Observer.Element
typealias Parent = ObservableOptionalScheduled<Element>
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<Element>: Producer<Element> {
fileprivate let _optional: Element?
fileprivate let _scheduler: ImmediateSchedulerType
init(optional: Element?, scheduler: ImmediateSchedulerType) {
self._optional = optional
self._scheduler = scheduler
}
override func run<Observer: ObserverType>(_ 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<Element>: Producer<Element> {
private let _optional: Element?
init(optional: Element?) {
self._optional = optional
}
override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
if let element = self._optional {
observer.on(.next(element))
}
observer.on(.completed)
return Disposables.create()
}
}
//
// 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 class Foundation.Thread
import protocol Foundation.NSCopying
extension Thread {
static func setThreadLocalStorageValue<T: AnyObject>(_ 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<T>(_ key: NSCopying) -> T? {
let currentThread = Thread.current
let threadDictionary = currentThread.threadDictionary
return threadDictionary[key] as? T
}
}
#endif
//
// Platform.Linux.swift
// Platform
//
// Created by Krunoslav Zaher on 12/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(Linux)
import class Foundation.Thread
extension Thread {
static func setThreadLocalStorageValue<T: AnyObject>(_ value: T?, forKey key: String) {
if let newValue = value {
Thread.current.threadDictionary[key] = newValue
}
else {
Thread.current.threadDictionary[key] = nil
}
}
static func getThreadLocalStorageValueForKey<T: AnyObject>(_ key: String) -> T? {
let currentThread = Thread.current
let threadDictionary = currentThread.threadDictionary
return threadDictionary[key] as? T
}
}
#endif
// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project
//
// PrimitiveSequence+Zip+arity.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/23/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
// 2
extension PrimitiveSequenceType where Trait == SingleTrait {
/**
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<E1, E2>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, resultSelector: @escaping (E1, E2) throws -> Element)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where Element == Any, Trait == SingleTrait {
/**
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 using the specified result selector function.
*/
public static func zip<E1, E2>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>)
-> PrimitiveSequence<Trait, (E1, E2)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable())
)
}
}
extension PrimitiveSequenceType where Trait == MaybeTrait {
/**
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<E1, E2>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, resultSelector: @escaping (E1, E2) throws -> Element)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where Element == Any, Trait == MaybeTrait {
/**
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 using the specified result selector function.
*/
public static func zip<E1, E2>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>)
-> PrimitiveSequence<Trait, (E1, E2)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable())
)
}
}
// 3
extension PrimitiveSequenceType where Trait == SingleTrait {
/**
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<E1, E2, E3>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, resultSelector: @escaping (E1, E2, E3) throws -> Element)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where Element == Any, Trait == SingleTrait {
/**
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 using the specified result selector function.
*/
public static func zip<E1, E2, E3>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>)
-> PrimitiveSequence<Trait, (E1, E2, E3)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable())
)
}
}
extension PrimitiveSequenceType where Trait == MaybeTrait {
/**
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<E1, E2, E3>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, resultSelector: @escaping (E1, E2, E3) throws -> Element)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where Element == Any, Trait == MaybeTrait {
/**
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 using the specified result selector function.
*/
public static func zip<E1, E2, E3>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>)
-> PrimitiveSequence<Trait, (E1, E2, E3)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable())
)
}
}
// 4
extension PrimitiveSequenceType where Trait == SingleTrait {
/**
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<E1, E2, E3, E4>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, resultSelector: @escaping (E1, E2, E3, E4) throws -> Element)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where Element == Any, Trait == SingleTrait {
/**
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 using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>)
-> PrimitiveSequence<Trait, (E1, E2, E3, E4)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable())
)
}
}
extension PrimitiveSequenceType where Trait == MaybeTrait {
/**
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<E1, E2, E3, E4>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, resultSelector: @escaping (E1, E2, E3, E4) throws -> Element)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where Element == Any, Trait == MaybeTrait {
/**
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 using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>)
-> PrimitiveSequence<Trait, (E1, E2, E3, E4)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable())
)
}
}
// 5
extension PrimitiveSequenceType where Trait == SingleTrait {
/**
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<E1, E2, E3, E4, E5>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, _ source5: PrimitiveSequence<Trait, E5>, resultSelector: @escaping (E1, E2, E3, E4, E5) throws -> Element)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where Element == Any, Trait == SingleTrait {
/**
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 using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, _ source5: PrimitiveSequence<Trait, E5>)
-> PrimitiveSequence<Trait, (E1, E2, E3, E4, E5)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable())
)
}
}
extension PrimitiveSequenceType where Trait == MaybeTrait {
/**
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<E1, E2, E3, E4, E5>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, _ source5: PrimitiveSequence<Trait, E5>, resultSelector: @escaping (E1, E2, E3, E4, E5) throws -> Element)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where Element == Any, Trait == MaybeTrait {
/**
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 using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, _ source5: PrimitiveSequence<Trait, E5>)
-> PrimitiveSequence<Trait, (E1, E2, E3, E4, E5)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable())
)
}
}
// 6
extension PrimitiveSequenceType where Trait == SingleTrait {
/**
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<E1, E2, E3, E4, E5, E6>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, _ source5: PrimitiveSequence<Trait, E5>, _ source6: PrimitiveSequence<Trait, E6>, resultSelector: @escaping (E1, E2, E3, E4, E5, E6) throws -> Element)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where Element == Any, Trait == SingleTrait {
/**
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 using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, _ source5: PrimitiveSequence<Trait, E5>, _ source6: PrimitiveSequence<Trait, E6>)
-> PrimitiveSequence<Trait, (E1, E2, E3, E4, E5, E6)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable())
)
}
}
extension PrimitiveSequenceType where Trait == MaybeTrait {
/**
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<E1, E2, E3, E4, E5, E6>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, _ source5: PrimitiveSequence<Trait, E5>, _ source6: PrimitiveSequence<Trait, E6>, resultSelector: @escaping (E1, E2, E3, E4, E5, E6) throws -> Element)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where Element == Any, Trait == MaybeTrait {
/**
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 using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, _ source5: PrimitiveSequence<Trait, E5>, _ source6: PrimitiveSequence<Trait, E6>)
-> PrimitiveSequence<Trait, (E1, E2, E3, E4, E5, E6)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable())
)
}
}
// 7
extension PrimitiveSequenceType where Trait == SingleTrait {
/**
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<E1, E2, E3, E4, E5, E6, E7>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, _ source5: PrimitiveSequence<Trait, E5>, _ source6: PrimitiveSequence<Trait, E6>, _ source7: PrimitiveSequence<Trait, E7>, resultSelector: @escaping (E1, E2, E3, E4, E5, E6, E7) throws -> Element)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(), source7.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where Element == Any, Trait == SingleTrait {
/**
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 using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6, E7>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, _ source5: PrimitiveSequence<Trait, E5>, _ source6: PrimitiveSequence<Trait, E6>, _ source7: PrimitiveSequence<Trait, E7>)
-> PrimitiveSequence<Trait, (E1, E2, E3, E4, E5, E6, E7)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(), source7.asObservable())
)
}
}
extension PrimitiveSequenceType where Trait == MaybeTrait {
/**
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<E1, E2, E3, E4, E5, E6, E7>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, _ source5: PrimitiveSequence<Trait, E5>, _ source6: PrimitiveSequence<Trait, E6>, _ source7: PrimitiveSequence<Trait, E7>, resultSelector: @escaping (E1, E2, E3, E4, E5, E6, E7) throws -> Element)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(), source7.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where Element == Any, Trait == MaybeTrait {
/**
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 using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6, E7>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, _ source5: PrimitiveSequence<Trait, E5>, _ source6: PrimitiveSequence<Trait, E6>, _ source7: PrimitiveSequence<Trait, E7>)
-> PrimitiveSequence<Trait, (E1, E2, E3, E4, E5, E6, E7)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(), source7.asObservable())
)
}
}
// 8
extension PrimitiveSequenceType where Trait == SingleTrait {
/**
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<E1, E2, E3, E4, E5, E6, E7, E8>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, _ source5: PrimitiveSequence<Trait, E5>, _ source6: PrimitiveSequence<Trait, E6>, _ source7: PrimitiveSequence<Trait, E7>, _ source8: PrimitiveSequence<Trait, E8>, resultSelector: @escaping (E1, E2, E3, E4, E5, E6, E7, E8) throws -> Element)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(), source7.asObservable(), source8.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where Element == Any, Trait == SingleTrait {
/**
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 using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6, E7, E8>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, _ source5: PrimitiveSequence<Trait, E5>, _ source6: PrimitiveSequence<Trait, E6>, _ source7: PrimitiveSequence<Trait, E7>, _ source8: PrimitiveSequence<Trait, E8>)
-> PrimitiveSequence<Trait, (E1, E2, E3, E4, E5, E6, E7, E8)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(), source7.asObservable(), source8.asObservable())
)
}
}
extension PrimitiveSequenceType where Trait == MaybeTrait {
/**
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<E1, E2, E3, E4, E5, E6, E7, E8>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, _ source5: PrimitiveSequence<Trait, E5>, _ source6: PrimitiveSequence<Trait, E6>, _ source7: PrimitiveSequence<Trait, E7>, _ source8: PrimitiveSequence<Trait, E8>, resultSelector: @escaping (E1, E2, E3, E4, E5, E6, E7, E8) throws -> Element)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(), source7.asObservable(), source8.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where Element == Any, Trait == MaybeTrait {
/**
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 using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6, E7, E8>(_ source1: PrimitiveSequence<Trait, E1>, _ source2: PrimitiveSequence<Trait, E2>, _ source3: PrimitiveSequence<Trait, E3>, _ source4: PrimitiveSequence<Trait, E4>, _ source5: PrimitiveSequence<Trait, E5>, _ source6: PrimitiveSequence<Trait, E6>, _ source7: PrimitiveSequence<Trait, E7>, _ source8: PrimitiveSequence<Trait, E8>)
-> PrimitiveSequence<Trait, (E1, E2, E3, E4, E5, E6, E7, E8)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(), source7.asObservable(), source8.asObservable())
)
}
}
//
// PrimitiveSequence.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/5/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
/// Observable sequences containing 0 or 1 element.
public struct PrimitiveSequence<Trait, Element> {
let source: Observable<Element>
init(raw: Observable<Element>) {
self.source = raw
}
}
/// Observable sequences containing 0 or 1 element
public protocol PrimitiveSequenceType {
/// Additional constraints
associatedtype Trait
/// Sequence element type
associatedtype Element
@available(*, deprecated, renamed: "Trait")
typealias TraitType = Trait
@available(*, deprecated, renamed: "Element")
typealias ElementType = Element
// Converts `self` to primitive sequence.
///
/// - returns: Observable sequence that represents `self`.
var primitiveSequence: PrimitiveSequence<Trait, Element> { get }
}
extension PrimitiveSequence: PrimitiveSequenceType {
// Converts `self` to primitive sequence.
///
/// - returns: Observable sequence that represents `self`.
public var primitiveSequence: PrimitiveSequence<Trait, Element> {
return self
}
}
extension PrimitiveSequence: ObservableConvertibleType {
/// Converts `self` to `Observable` sequence.
///
/// - returns: Observable sequence that represents `self`.
public func asObservable() -> Observable<Element> {
return self.source
}
}
extension PrimitiveSequence {
/**
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 -> PrimitiveSequence<Trait, Element>)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.deferred {
try observableFactory().asObservable()
})
}
/**
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)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: self.primitiveSequence.source.delay(dueTime, scheduler: scheduler))
}
/**
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)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: self.source.delaySubscription(dueTime, scheduler: scheduler))
}
/**
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 observeOn(_ scheduler: ImmediateSchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: self.source.observeOn(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.
*/
public func subscribeOn(_ scheduler: ImmediateSchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: self.source.subscribeOn(scheduler))
}
/**
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 catchError(_ handler: @escaping (Swift.Error) throws -> PrimitiveSequence<Trait, Element>)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: self.source.catchError { try handler($0).asObservable() })
}
/**
If the initial subscription to the observable sequence emits an error event, try repeating it up to the specified number of attempts (inclusive of the initial attempt) or until is succeeds. For example, if you want to retry a sequence once upon failure, you should use retry(2) (once for the initial attempt, and once for the retry).
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter maxAttemptCount: Maximum number of times to attempt the sequence subscription.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
public func retry(_ maxAttemptCount: Int)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: self.source.retry(maxAttemptCount))
}
/**
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 retryWhen<TriggerObservable: ObservableType, Error: Swift.Error>(_ notificationHandler: @escaping (Observable<Error>) -> TriggerObservable)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: self.source.retryWhen(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 retryWhen<TriggerObservable: ObservableType>(_ notificationHandler: @escaping (Observable<Swift.Error>) -> TriggerObservable)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: self.source.retryWhen(notificationHandler))
}
/**
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)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: self.source.debug(identifier, trimOutput: trimOutput, file: file, line: line, function: function))
}
/**
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 primitiveSequenceFactory: 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<Resource: Disposable>(_ resourceFactory: @escaping () throws -> Resource, primitiveSequenceFactory: @escaping (Resource) throws -> PrimitiveSequence<Trait, Element>)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.using(resourceFactory, observableFactory: { (resource: Resource) throws -> Observable<Element> in
return try primitiveSequenceFactory(resource).asObservable()
}))
}
/**
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)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence<Trait, Element>(raw: self.primitiveSequence.source.timeout(dueTime, 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: PrimitiveSequence<Trait, Element>,
scheduler: SchedulerType) -> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence<Trait, Element>(raw: self.primitiveSequence.source.timeout(dueTime, other: other.source, scheduler: scheduler))
}
}
extension PrimitiveSequenceType 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 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, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable<Element>.timer(dueTime, scheduler: scheduler))
}
}
//
// PriorityQueue.swift
// Platform
//
// Created by Krunoslav Zaher on 12/27/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
struct PriorityQueue<Element> {
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) {
_hasHigherPriority = hasHigherPriority
_isEqual = isEqual
}
mutating func enqueue(_ element: Element) {
_elements.append(element)
bubbleToHigherPriority(_elements.count - 1)
}
func peek() -> Element? {
return _elements.first
}
var isEmpty: Bool {
return _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 _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 _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 && _hasHigherPriority(_elements[leftChildIndex], _elements[highestPriorityIndex]) {
highestPriorityIndex = leftChildIndex
}
if rightChildIndex < _elements.count && _hasHigherPriority(_elements[rightChildIndex], _elements[highestPriorityIndex]) {
highestPriorityIndex = rightChildIndex
}
guard highestPriorityIndex != unbalancedIndex else { break }
_elements.swapAt(highestPriorityIndex, unbalancedIndex)
unbalancedIndex = highestPriorityIndex
}
}
}
extension PriorityQueue : CustomDebugStringConvertible {
var debugDescription: String {
return _elements.debugDescription
}
}
//
// Producer.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/20/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
class Producer<Element> : Observable<Element> {
override init() {
super.init()
}
override func subscribe<Observer: ObserverType>(_ 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: ObserverType>(_ 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 {
return 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
}
}
}
//
// PublishSubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/11/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// Represents an object that is both an observable sequence as well as an observer.
///
/// Each notification is broadcasted to all subscribed observers.
public final class PublishSubject<Element>
: Observable<Element>
, SubjectType
, Cancelable
, ObserverType
, SynchronizedUnsubscribeType {
public typealias SubjectObserverType = PublishSubject<Element>
typealias Observers = AnyObserver<Element>.s
typealias DisposeKey = Observers.KeyType
/// Indicates whether the subject has any observers
public var hasObservers: Bool {
self._lock.lock()
let count = self._observers.count > 0
self._lock.unlock()
return count
}
private let _lock = RecursiveLock()
// state
private var _isDisposed = false
private var _observers = Observers()
private var _stopped = false
private var _stoppedEvent = nil as Event<Element>?
#if DEBUG
private let _synchronizationTracker = SynchronizationTracker()
#endif
/// Indicates whether the subject has been isDisposed.
public var isDisposed: Bool {
return self._isDisposed
}
/// Creates a subject.
public override init() {
super.init()
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
}
/// Notifies all subscribed observers about next event.
///
/// - parameter event: Event to send to the observers.
public func on(_ event: Event<Element>) {
#if DEBUG
self._synchronizationTracker.register(synchronizationErrorMessage: .default)
defer { self._synchronizationTracker.unregister() }
#endif
dispatch(self._synchronized_on(event), event)
}
func _synchronized_on(_ event: Event<Element>) -> Observers {
self._lock.lock(); defer { self._lock.unlock() }
switch event {
case .next:
if self._isDisposed || self._stopped {
return Observers()
}
return self._observers
case .completed, .error:
if self._stoppedEvent == nil {
self._stoppedEvent = event
self._stopped = true
let observers = self._observers
self._observers.removeAll()
return observers
}
return Observers()
}
}
/**
Subscribes an observer to the subject.
- parameter observer: Observer to subscribe to the subject.
- returns: Disposable object that can be used to unsubscribe the observer from the subject.
*/
public override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
self._lock.lock()
let subscription = self._synchronized_subscribe(observer)
self._lock.unlock()
return subscription
}
func _synchronized_subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
if let stoppedEvent = self._stoppedEvent {
observer.on(stoppedEvent)
return Disposables.create()
}
if self._isDisposed {
observer.on(.error(RxError.disposed(object: self)))
return Disposables.create()
}
let key = self._observers.insert(observer.on)
return SubscriptionDisposable(owner: self, key: key)
}
func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
self._lock.lock()
self._synchronized_unsubscribe(disposeKey)
self._lock.unlock()
}
func _synchronized_unsubscribe(_ disposeKey: DisposeKey) {
_ = self._observers.removeKey(disposeKey)
}
/// Returns observer interface for subject.
public func asObserver() -> PublishSubject<Element> {
return self
}
/// Unsubscribe all observers and release resources.
public func dispose() {
self._lock.lock()
self._synchronized_dispose()
self._lock.unlock()
}
final func _synchronized_dispose() {
self._isDisposed = true
self._observers.removeAll()
self._stoppedEvent = nil
}
#if TRACE_RESOURCES
deinit {
_ = Resources.decrementTotal()
}
#endif
}
//
// 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<T>: Sequence {
/// Type of generator.
typealias Generator = AnyIterator<T>
private let _resizeFactor = 2
private var _storage: ContiguousArray<T?>
private var _count = 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<T?>(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 {
return count == 0
}
/// - returns: Number of elements inside queue.
var count: Int {
return _count
}
/// - 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<T?>(repeating: nil, count: size)
let count = _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]
_count = 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
_count += 1
if _pushNextIndex >= _storage.count {
_pushNextIndex -= _storage.count
}
}
private mutating func dequeueElementOnly() -> T {
precondition(count > 0)
let index = dequeueIndex
defer {
_storage[index] = nil
_count -= 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<T> {
var i = dequeueIndex
var count = _count
return AnyIterator {
if count == 0 {
return nil
}
defer {
count -= 1
i += 1
}
if i >= self._storage.count {
i -= self._storage.count
}
return self._storage[i]
}
}
}
//
// 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<Element> {
return RangeProducer<Element>(start: start, count: count, scheduler: scheduler)
}
}
final private class RangeProducer<Element: RxAbstractInteger>: Producer<Element> {
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: ObserverType>(_ 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<Observer: ObserverType>: Sink<Observer> where Observer.Element: RxAbstractInteger {
typealias Parent = RangeProducer<Observer.Element>
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()
}
}
}
}
//
// 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.
*/
public struct Reactive<Base> {
/// Base object to extend.
public let base: Base
/// Creates extensions with base object.
///
/// - parameter base: Base object.
public init(_ base: Base) {
self.base = base
}
}
/// A type that has reactive extensions.
public protocol ReactiveCompatible {
/// Extended type
associatedtype ReactiveBase
@available(*, deprecated, renamed: "ReactiveBase")
typealias CompatibleType = ReactiveBase
/// Reactive extensions.
static var rx: Reactive<ReactiveBase>.Type { get set }
/// Reactive extensions.
var rx: Reactive<ReactiveBase> { get set }
}
extension ReactiveCompatible {
/// Reactive extensions.
public static var rx: Reactive<Self>.Type {
get {
return Reactive<Self>.self
}
// swiftlint:disable:next unused_setter_value
set {
// this enables using Reactive to "mutate" base type
}
}
/// Reactive extensions.
public var rx: Reactive<Self> {
get {
return Reactive(self)
}
// swiftlint:disable:next unused_setter_value
set {
// this enables using Reactive to "mutate" base object
}
}
}
import class Foundation.NSObject
/// Extend NSObject with `rx` proxy.
extension NSObject: ReactiveCompatible { }
//
// RecursiveLock.swift
// Platform
//
// Created by Krunoslav Zaher on 12/18/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import class Foundation.NSRecursiveLock
#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
//
// 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<State> {
typealias Action = (State, AnyRecursiveScheduler<State>) -> 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.calculateLocked { () -> 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.calculateLocked { () -> 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<State> {
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.calculateLocked { () -> 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()
}
}
//
// 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<A, Result>(_ seed: A, accumulator: @escaping (A, Element) throws -> A, mapResult: @escaping (A) throws -> Result)
-> Observable<Result> {
return 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<A>(_ seed: A, accumulator: @escaping (A, Element) throws -> A)
-> Observable<A> {
return Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: { $0 })
}
}
final private class ReduceSink<SourceType, AccumulateType, Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias ResultType = Observer.Element
typealias Parent = Reduce<SourceType, AccumulateType, ResultType>
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<SourceType>) {
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<SourceType, AccumulateType, ResultType>: Producer<ResultType> {
typealias AccumulatorType = (AccumulateType, SourceType) throws -> AccumulateType
typealias ResultSelectorType = (AccumulateType) throws -> ResultType
private let _source: Observable<SourceType>
fileprivate let _seed: AccumulateType
fileprivate let _accumulator: AccumulatorType
fileprivate let _mapResult: ResultSelectorType
init(source: Observable<SourceType>, seed: AccumulateType, accumulator: @escaping AccumulatorType, mapResult: @escaping ResultSelectorType) {
self._source = source
self._seed = seed
self._accumulator = accumulator
self._mapResult = mapResult
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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.lock(); defer { self._lock.unlock() }
return 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 {
return self._lock.calculateLocked {
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.calculateLocked {
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.calculateLocked {
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()
}
}
}
//
// 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<Element> {
return RepeatElement(element: element, scheduler: scheduler)
}
}
final private class RepeatElement<Element>: Producer<Element> {
fileprivate let _element: Element
fileprivate let _scheduler: ImmediateSchedulerType
init(element: Element, scheduler: ImmediateSchedulerType) {
self._element = element
self._scheduler = scheduler
}
override func run<Observer: ObserverType>(_ 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<Observer: ObserverType>: Sink<Observer> {
typealias Parent = RepeatElement<Observer.Element>
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)
}
}
}
//
// ReplaySubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 4/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// Represents an object that is both an observable sequence as well as an observer.
///
/// Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
public class ReplaySubject<Element>
: Observable<Element>
, SubjectType
, ObserverType
, Disposable {
public typealias SubjectObserverType = ReplaySubject<Element>
typealias Observers = AnyObserver<Element>.s
typealias DisposeKey = Observers.KeyType
/// Indicates whether the subject has any observers
public var hasObservers: Bool {
self._lock.lock()
let value = self._observers.count > 0
self._lock.unlock()
return value
}
fileprivate let _lock = RecursiveLock()
// state
fileprivate var _isDisposed = false
fileprivate var _isStopped = false
fileprivate var _stoppedEvent = nil as Event<Element>? {
didSet {
self._isStopped = self._stoppedEvent != nil
}
}
fileprivate var _observers = Observers()
#if DEBUG
fileprivate let _synchronizationTracker = SynchronizationTracker()
#endif
func unsubscribe(_ key: DisposeKey) {
rxAbstractMethod()
}
final var isStopped: Bool {
return self._isStopped
}
/// Notifies all subscribed observers about next event.
///
/// - parameter event: Event to send to the observers.
public func on(_ event: Event<Element>) {
rxAbstractMethod()
}
/// Returns observer interface for subject.
public func asObserver() -> SubjectObserverType {
return self
}
/// Unsubscribe all observers and release resources.
public func dispose() {
}
/// Creates new instance of `ReplaySubject` that replays at most `bufferSize` last elements of sequence.
///
/// - parameter bufferSize: Maximal number of elements to replay to observer after subscription.
/// - returns: New instance of replay subject.
public static func create(bufferSize: Int) -> ReplaySubject<Element> {
if bufferSize == 1 {
return ReplayOne()
}
else {
return ReplayMany(bufferSize: bufferSize)
}
}
/// Creates a new instance of `ReplaySubject` that buffers all the elements of a sequence.
/// To avoid filling up memory, developer needs to make sure that the use case will only ever store a 'reasonable'
/// number of elements.
public static func createUnbounded() -> ReplaySubject<Element> {
return ReplayAll()
}
#if TRACE_RESOURCES
override init() {
_ = Resources.incrementTotal()
}
deinit {
_ = Resources.decrementTotal()
}
#endif
}
private class ReplayBufferBase<Element>
: ReplaySubject<Element>
, SynchronizedUnsubscribeType {
func trim() {
rxAbstractMethod()
}
func addValueToBuffer(_ value: Element) {
rxAbstractMethod()
}
func replayBuffer<Observer: ObserverType>(_ observer: Observer) where Observer.Element == Element {
rxAbstractMethod()
}
override func on(_ event: Event<Element>) {
#if DEBUG
self._synchronizationTracker.register(synchronizationErrorMessage: .default)
defer { self._synchronizationTracker.unregister() }
#endif
dispatch(self._synchronized_on(event), event)
}
func _synchronized_on(_ event: Event<Element>) -> Observers {
self._lock.lock(); defer { self._lock.unlock() }
if self._isDisposed {
return Observers()
}
if self._isStopped {
return Observers()
}
switch event {
case .next(let element):
self.addValueToBuffer(element)
self.trim()
return self._observers
case .error, .completed:
self._stoppedEvent = event
self.trim()
let observers = self._observers
self._observers.removeAll()
return observers
}
}
override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
self._lock.lock()
let subscription = self._synchronized_subscribe(observer)
self._lock.unlock()
return subscription
}
func _synchronized_subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
if self._isDisposed {
observer.on(.error(RxError.disposed(object: self)))
return Disposables.create()
}
let anyObserver = observer.asObserver()
self.replayBuffer(anyObserver)
if let stoppedEvent = self._stoppedEvent {
observer.on(stoppedEvent)
return Disposables.create()
}
else {
let key = self._observers.insert(observer.on)
return SubscriptionDisposable(owner: self, key: key)
}
}
func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
self._lock.lock()
self._synchronized_unsubscribe(disposeKey)
self._lock.unlock()
}
func _synchronized_unsubscribe(_ disposeKey: DisposeKey) {
if self._isDisposed {
return
}
_ = self._observers.removeKey(disposeKey)
}
override func dispose() {
super.dispose()
self.synchronizedDispose()
}
func synchronizedDispose() {
self._lock.lock()
self._synchronized_dispose()
self._lock.unlock()
}
func _synchronized_dispose() {
self._isDisposed = true
self._observers.removeAll()
}
}
private final class ReplayOne<Element> : ReplayBufferBase<Element> {
private var _value: Element?
override init() {
super.init()
}
override func trim() {
}
override func addValueToBuffer(_ value: Element) {
self._value = value
}
override func replayBuffer<Observer: ObserverType>(_ observer: Observer) where Observer.Element == Element {
if let value = self._value {
observer.on(.next(value))
}
}
override func _synchronized_dispose() {
super._synchronized_dispose()
self._value = nil
}
}
private class ReplayManyBase<Element>: ReplayBufferBase<Element> {
fileprivate var _queue: Queue<Element>
init(queueSize: Int) {
self._queue = Queue(capacity: queueSize + 1)
}
override func addValueToBuffer(_ value: Element) {
self._queue.enqueue(value)
}
override func replayBuffer<Observer: ObserverType>(_ observer: Observer) where Observer.Element == Element {
for item in self._queue {
observer.on(.next(item))
}
}
override func _synchronized_dispose() {
super._synchronized_dispose()
self._queue = Queue(capacity: 0)
}
}
private final class ReplayMany<Element> : ReplayManyBase<Element> {
private let _bufferSize: Int
init(bufferSize: Int) {
self._bufferSize = bufferSize
super.init(queueSize: bufferSize)
}
override func trim() {
while self._queue.count > self._bufferSize {
_ = self._queue.dequeue()
}
}
}
private final class ReplayAll<Element> : ReplayManyBase<Element> {
init() {
super.init(queueSize: 0)
}
override func trim() {
}
}
//
// 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 retryWhen<TriggerObservable: ObservableType, Error: Swift.Error>(_ notificationHandler: @escaping (Observable<Error>) -> TriggerObservable)
-> Observable<Element> {
return 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.
*/
public func retryWhen<TriggerObservable: ObservableType>(_ notificationHandler: @escaping (Observable<Swift.Error>) -> TriggerObservable)
-> Observable<Element> {
return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler)
}
}
final private class RetryTriggerSink<Sequence: Swift.Sequence, Observer: ObserverType, TriggerObservable: ObservableType, Error>
: ObserverType where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element {
typealias Element = TriggerObservable.Element
typealias Parent = RetryWhenSequenceSinkIter<Sequence, Observer, TriggerObservable, Error>
private let _parent: Parent
init(parent: Parent) {
self._parent = parent
}
func on(_ event: Event<Element>) {
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<Sequence: Swift.Sequence, Observer: ObserverType, TriggerObservable: ObservableType, Error>
: ObserverType
, Disposable where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element {
typealias Element = Observer.Element
typealias Parent = RetryWhenSequenceSink<Sequence, Observer, TriggerObservable, Error>
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<Element>) {
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<Sequence: Swift.Sequence, Observer: ObserverType, TriggerObservable: ObservableType, Error>
: TailRecursiveSink<Sequence, Observer> where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element {
typealias Element = Observer.Element
typealias Parent = RetryWhenSequence<Sequence, TriggerObservable, Error>
let _lock = RecursiveLock()
private let _parent: Parent
fileprivate var _lastError: Swift.Error?
fileprivate let _errorSubject = PublishSubject<Error>()
private let _handler: Observable<TriggerObservable.Element>
fileprivate let _notifier = PublishSubject<TriggerObservable.Element>()
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<Element>) -> SequenceGenerator? {
// It is important to always return `nil` here because there are sideffects 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<Element>) -> 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<Sequence: Swift.Sequence, TriggerObservable: ObservableType, Error>: Producer<Sequence.Element.Element> where Sequence.Element: ObservableType {
typealias Element = Sequence.Element.Element
private let _sources: Sequence
fileprivate let _notificationHandler: (Observable<Error>) -> TriggerObservable
init(sources: Sequence, notificationHandler: @escaping (Observable<Error>) -> TriggerObservable) {
self._sources = sources
self._notificationHandler = notificationHandler
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = RetryWhenSequenceSink<Sequence, Observer, TriggerObservable, Error>(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run((self._sources.makeIterator(), nil))
return (sink: sink, subscription: subscription)
}
}
//
// 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 {
return load(resourceCount)
}
/// Increments `Resources.total` resource count.
///
/// - returns: New resource count
public static func incrementTotal() -> Int32 {
return increment(resourceCount)
}
/// Decrements `Resources.total` resource count
///
/// - returns: New resource count
public static func decrementTotal() -> Int32 {
return 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 class Foundation.Thread
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 `.observeOn(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 `.observeOn(MainScheduler.asyncInstance)`\n" +
" or by synchronizing sequence events in some other way.\n"
)
}
}
func unregister() {
self._lock.lock(); defer { self._lock.unlock() }
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
}
//
// 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<String, Any>`: 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 class Foundation.NSObject
/// Creates mutable reference wrapper for any type.
final class RxMutableBox<T>: 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<T>: 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 {
return "MutatingBox(\(self.value))"
}
}
#endif
//
// 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, no element is sent to the resulting sequence.**
- seealso: [sample operator on reactivex.io](http://reactivex.io/documentation/operators/sample.html)
- parameter sampler: Sampling tick sequence.
- returns: Sampled observable sequence.
*/
public func sample<Source: ObservableType>(_ sampler: Source)
-> Observable<Element> {
return Sample(source: self.asObservable(), sampler: sampler.asObservable())
}
}
final private class SamplerSink<Observer: ObserverType, SampleType>
: ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = SampleType
typealias Parent = SampleSequenceSink<Observer, SampleType>
private let _parent: Parent
var _lock: RecursiveLock {
return self._parent._lock
}
init(parent: Parent) {
self._parent = parent
}
func on(_ event: Event<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
switch event {
case .next, .completed:
if let element = _parent._element {
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<Observer: ObserverType, SampleType>
: Sink<Observer>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = Observer.Element
typealias Parent = Sample<Element, SampleType>
private let _parent: Parent
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) {
self._parent = parent
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<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
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<Element, SampleType>: Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _sampler: Observable<SampleType>
init(source: Observable<Element>, sampler: Observable<SampleType>) {
self._source = source
self._sampler = sampler
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = SampleSequenceSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
//
// 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<A>(into seed: A, accumulator: @escaping (inout A, Element) throws -> Void)
-> Observable<A> {
return 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<A>(_ seed: A, accumulator: @escaping (A, Element) throws -> A)
-> Observable<A> {
return Scan(source: self.asObservable(), seed: seed) { acc, element in
let currentAcc = acc
acc = try accumulator(currentAcc, element)
}
}
}
final private class ScanSink<Element, Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias Accumulate = Observer.Element
typealias Parent = Scan<Element, Accumulate>
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<Element>) {
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<Element, Accumulate>: Producer<Accumulate> {
typealias Accumulator = (inout Accumulate, Element) throws -> Void
private let _source: Observable<Element>
fileprivate let _seed: Accumulate
fileprivate let _accumulator: Accumulator
init(source: Observable<Element>, seed: Accumulate, accumulator: @escaping Accumulator) {
self._source = source
self._seed = seed
self._accumulator = accumulator
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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 _isDisposed = AtomicInt(0)
// state
private var _disposable: Disposable?
/// - returns: Was resource disposed.
public var isDisposed: Bool {
return isFlagSet(self._isDisposed, 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._isDisposed, 1) == 0 {
self._disposable!.dispose()
self._disposable = nil
}
}
}
//
// ScheduledItem.swift
// RxSwift
//
// Created by Krunoslav Zaher on 9/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
struct ScheduledItem<T>
: ScheduledItemType
, InvocableType {
typealias Action = (T) -> Disposable
private let _action: Action
private let _state: T
private let _disposable = SingleAssignmentDisposable()
var isDisposed: Bool {
return 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()
}
}
//
// ScheduledItemType.swift
// RxSwift
//
// Created by Krunoslav Zaher on 11/7/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
protocol ScheduledItemType
: Cancelable
, InvocableType {
func invoke()
}
//
// 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<State> {
typealias RecursiveAction = (State) -> State
typealias RecursiveScheduler = AnyRecursiveScheduler<SchedulePeriodicRecursiveCommand>
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 {
return 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)
}
}
}
}
//
// SchedulerType.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import enum Dispatch.DispatchTimeInterval
import struct Foundation.Date
// 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<StateType>(_ 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<StateType>(_ 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<StateType>(_ 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: State, dueTime: RxTimeInterval, action: @escaping (State, AnyRecursiveScheduler<State>) -> Void) -> Disposable {
let scheduler = AnyRecursiveScheduler(scheduler: self, action: action)
scheduler.schedule(state, dueTime: dueTime)
return Disposables.create(with: scheduler.dispose)
}
}
//
// 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<Element> {
return 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<Element> {
return ObservableSequence(elements: array, scheduler: scheduler)
}
/**
Converts a sequence to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
public static func from<Sequence: Swift.Sequence>(_ sequence: Sequence, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<Element> where Sequence.Element == Element {
return ObservableSequence(elements: sequence, scheduler: scheduler)
}
}
final private class ObservableSequenceSink<Sequence: Swift.Sequence, Observer: ObserverType>: Sink<Observer> where Sequence.Element == Observer.Element {
typealias Parent = ObservableSequence<Sequence>
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<Sequence: Swift.Sequence>: Producer<Sequence.Element> {
fileprivate let _elements: Sequence
fileprivate let _scheduler: ImmediateSchedulerType
init(elements: Sequence, scheduler: ImmediateSchedulerType) {
self._elements = elements
self._scheduler = scheduler
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// SerialDispatchQueueScheduler.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import struct Foundation.TimeInterval
import struct Foundation.Date
import Dispatch
/**
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 {
return 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(iOS 8, OSX 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<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
return self.scheduleInternal(state, action: action)
}
func scheduleInternal<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
return 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<StateType>(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable {
return 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<StateType>(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable {
return self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action)
}
}
//
// 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 _isDisposed = false
/// - returns: Was resource disposed.
public var isDisposed: Bool {
return self._isDisposed
}
/// 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 {
return self._lock.calculateLocked {
return self._current ?? Disposables.create()
}
}
set (newDisposable) {
let disposable: Disposable? = self._lock.calculateLocked {
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.lock(); defer { self._lock.unlock() }
if self._isDisposed {
return nil
}
else {
self._isDisposed = true
let current = self._current
self._current = nil
return current
}
}
}
//
// 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<TimeInterval> 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<TimeInterval> 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<Element> {
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<Element>
: ObserverType
, SynchronizedUnsubscribeType {
typealias Observers = AnyObserver<Element>.s
typealias DisposeKey = Observers.KeyType
typealias Parent = ShareReplay1WhileConnected<Element>
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<Element>) {
self._lock.lock()
let observers = self._synchronized_on(event)
self._lock.unlock()
dispatch(observers, event)
}
final private func _synchronized_on(_ event: Event<Element>) -> 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: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
self._lock.lock(); defer { self._lock.unlock() }
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) {
self._lock.lock()
let shouldDisconnect = self._synchronized_unsubscribe(disposeKey)
self._lock.unlock()
if shouldDisconnect {
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<Element>
: Observable<Element> {
fileprivate typealias Connection = ShareReplay1WhileConnectedConnection<Element>
fileprivate let _source: Observable<Element>
private let _lock = RecursiveLock()
fileprivate var _connection: Connection?
init(source: Observable<Element>) {
self._source = source
}
override func subscribe<Observer: ObserverType>(_ 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: ObserverType>(_ observer: Observer) -> Connection where Observer.Element == Element {
let connection: Connection
if let existingConnection = self._connection {
connection = existingConnection
}
else {
connection = ShareReplay1WhileConnectedConnection<Element>(
parent: self,
lock: self._lock)
self._connection = connection
}
return connection
}
}
private final class ShareWhileConnectedConnection<Element>
: ObserverType
, SynchronizedUnsubscribeType {
typealias Observers = AnyObserver<Element>.s
typealias DisposeKey = Observers.KeyType
typealias Parent = ShareWhileConnected<Element>
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<Element>) {
self._lock.lock()
let observers = self._synchronized_on(event)
self._lock.unlock()
dispatch(observers, event)
}
final private func _synchronized_on(_ event: Event<Element>) -> 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: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
self._lock.lock(); defer { self._lock.unlock() }
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) {
self._lock.lock()
let shouldDisconnect = self._synchronized_unsubscribe(disposeKey)
self._lock.unlock()
if shouldDisconnect {
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<Element>
: Observable<Element> {
fileprivate typealias Connection = ShareWhileConnectedConnection<Element>
fileprivate let _source: Observable<Element>
private let _lock = RecursiveLock()
fileprivate var _connection: Connection?
init(source: Observable<Element>) {
self._source = source
}
override func subscribe<Observer: ObserverType>(_ 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: ObserverType>(_ observer: Observer) -> Connection where Observer.Element == Element {
let connection: Connection
if let existingConnection = self._connection {
connection = existingConnection
}
else {
connection = ShareWhileConnectedConnection<Element>(
parent: self,
lock: self._lock)
self._connection = connection
}
return connection
}
}
//
// Single.swift
// RxSwift
//
// Created by sergdort on 19/08/2017.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
#if DEBUG
import Foundation
#endif
/// Sequence containing exactly 1 element
public enum SingleTrait { }
/// Represents a push style sequence containing 1 element.
public typealias Single<Element> = PrimitiveSequence<SingleTrait, Element>
public enum SingleEvent<Element> {
/// One and only sequence element is produced. (underlying observable sequence emits: `.next(Element)`, `.completed`)
case success(Element)
/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)
case error(Swift.Error)
}
extension PrimitiveSequenceType where Trait == SingleTrait {
public typealias SingleObserver = (SingleEvent<Element>) -> Void
/**
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 (@escaping SingleObserver) -> Disposable) -> Single<Element> {
let source = Observable<Element>.create { observer in
return subscribe { event in
switch event {
case .success(let element):
observer.on(.next(element))
observer.on(.completed)
case .error(let error):
observer.on(.error(error))
}
}
}
return PrimitiveSequence(raw: source)
}
/**
Subscribes `observer` to receive events for this sequence.
- returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources.
*/
public func subscribe(_ observer: @escaping (SingleEvent<Element>) -> Void) -> Disposable {
var stopped = false
return self.primitiveSequence.asObservable().subscribe { event in
if stopped { return }
stopped = true
switch event {
case .next(let element):
observer(.success(element))
case .error(let error):
observer(.error(error))
case .completed:
rxFatalErrorInDebug("Singles can't emit a completion event")
}
}
}
/**
Subscribes a success handler, and an error handler for this sequence.
- parameter onSuccess: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onSuccess: ((Element) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil) -> Disposable {
#if DEBUG
let callStack = Hooks.recordCallStackOnError ? Thread.callStackSymbols : []
#else
let callStack = [String]()
#endif
return self.primitiveSequence.subscribe { event in
switch event {
case .success(let element):
onSuccess?(element)
case .error(let error):
if let onError = onError {
onError(error)
} else {
Hooks.defaultErrorHandler(callStack, error)
}
}
}
}
}
extension PrimitiveSequenceType where Trait == SingleTrait {
/**
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) -> Single<Element> {
return Single(raw: Observable.just(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) -> Single<Element> {
return Single(raw: Observable.just(element, scheduler: scheduler))
}
/**
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) -> Single<Element> {
return PrimitiveSequence(raw: Observable.error(error))
}
/**
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() -> Single<Element> {
return PrimitiveSequence(raw: Observable.never())
}
}
extension PrimitiveSequenceType where Trait == SingleTrait {
/**
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 onSuccess: Action to invoke for each element in the observable sequence.
- parameter afterSuccess: 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 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`(onSuccess: ((Element) throws -> Void)? = nil,
afterSuccess: ((Element) throws -> Void)? = nil,
onError: ((Swift.Error) throws -> Void)? = nil,
afterError: ((Swift.Error) throws -> Void)? = nil,
onSubscribe: (() -> Void)? = nil,
onSubscribed: (() -> Void)? = nil,
onDispose: (() -> Void)? = nil)
-> Single<Element> {
return Single(raw: self.primitiveSequence.source.do(
onNext: onSuccess,
afterNext: afterSuccess,
onError: onError,
afterError: afterError,
onSubscribe: onSubscribe,
onSubscribed: onSubscribed,
onDispose: onDispose)
)
}
/**
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)
-> Maybe<Element> {
return Maybe(raw: self.primitiveSequence.source.filter(predicate))
}
/**
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<Result>(_ transform: @escaping (Element) throws -> Result)
-> Single<Result> {
return Single(raw: self.primitiveSequence.source.map(transform))
}
/**
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.
- returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source.
*/
public func compactMap<Result>(_ transform: @escaping (Element) throws -> Result?)
-> Maybe<Result> {
return Maybe(raw: self.primitiveSequence.source.compactMap(transform))
}
/**
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<Result>(_ selector: @escaping (Element) throws -> Single<Result>)
-> Single<Result> {
return Single<Result>(raw: self.primitiveSequence.source.flatMap(selector))
}
/**
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 flatMapMaybe<Result>(_ selector: @escaping (Element) throws -> Maybe<Result>)
-> Maybe<Result> {
return Maybe<Result>(raw: self.primitiveSequence.source.flatMap(selector))
}
/**
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 flatMapCompletable(_ selector: @escaping (Element) throws -> Completable)
-> Completable {
return Completable(raw: self.primitiveSequence.source.flatMap(selector))
}
/**
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.
- 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: Swift.Collection, Result>(_ collection: Collection, resultSelector: @escaping ([Element]) throws -> Result) -> PrimitiveSequence<Trait, Result> where Collection.Element == PrimitiveSequence<Trait, Element> {
if collection.isEmpty {
return PrimitiveSequence<Trait, Result>.deferred {
return PrimitiveSequence<Trait, Result>(raw: .just(try resultSelector([])))
}
}
let raw = Observable.zip(collection.map { $0.asObservable() }, resultSelector: resultSelector)
return PrimitiveSequence<Trait, Result>(raw: raw)
}
/**
Merges the specified observable sequences into one observable sequence all of the observable sequences have produced an element at a corresponding index.
- returns: An observable sequence containing the result of combining elements of the sources.
*/
public static func zip<Collection: Swift.Collection>(_ collection: Collection) -> PrimitiveSequence<Trait, [Element]> where Collection.Element == PrimitiveSequence<Trait, Element> {
if collection.isEmpty {
return PrimitiveSequence<Trait, [Element]>(raw: .just([]))
}
let raw = Observable.zip(collection.map { $0.asObservable() })
return PrimitiveSequence(raw: raw)
}
/**
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 catchErrorJustReturn(_ element: Element)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: self.primitiveSequence.source.catchErrorJustReturn(element))
}
/// Converts `self` to `Maybe` trait.
///
/// - returns: Maybe trait that represents `self`.
public func asMaybe() -> Maybe<Element> {
return Maybe(raw: self.primitiveSequence.source)
}
/// Converts `self` to `Completable` trait.
///
/// - returns: Completable trait that represents `self`.
public func asCompletable() -> Completable {
return self.primitiveSequence.source.ignoreElements()
}
}
//
// 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 enum DisposeState: Int32 {
case disposed = 1
case disposableSet = 2
}
// 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 {
return 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
}
}
}
//
// 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<Element> {
return 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<Element> {
return SingleAsync(source: self.asObservable(), predicate: predicate)
}
}
private final class SingleAsyncSink<Observer: ObserverType> : Sink<Observer>, ObserverType {
typealias Element = Observer.Element
typealias Parent = SingleAsync<Element>
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<Element>) {
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<Element>: Producer<Element> {
typealias Predicate = (Element) throws -> Bool
private let _source: Observable<Element>
fileprivate let _predicate: Predicate?
init(source: Observable<Element>, predicate: Predicate? = nil) {
self._source = source
self._predicate = predicate
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// Sink.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
class Sink<Observer: ObserverType> : 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<Observer.Element>) {
#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<Observer> {
return SinkForward(forward: self)
}
final var disposed: Bool {
return isFlagSet(self._disposed, 1)
}
func dispose() {
fetchOr(self._disposed, 1)
self._cancel.dispose()
}
deinit {
#if TRACE_RESOURCES
_ = Resources.decrementTotal()
#endif
}
}
final class SinkForward<Observer: ObserverType>: ObserverType {
typealias Element = Observer.Element
private let _forward: Sink<Observer>
init(forward: Sink<Observer>) {
self._forward = forward
}
final func on(_ event: Event<Element>) {
switch event {
case .next:
self._forward._observer.on(event)
case .error, .completed:
self._forward._observer.on(event)
self._forward._cancel.dispose()
}
}
}
//
// 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<Element> {
return 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<Element> {
return SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler)
}
}
// count version
final private class SkipCountSink<Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias Element = Observer.Element
typealias Parent = SkipCount<Element>
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<Element>) {
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<Element>: Producer<Element> {
let source: Observable<Element>
let count: Int
init(source: Observable<Element>, count: Int) {
self.source = source
self.count = count
}
override func run<Observer: ObserverType>(_ 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<Element, Observer: ObserverType>: Sink<Observer>, ObserverType where Observer.Element == Element {
typealias Parent = SkipTime<Element>
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<Element>) {
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<Element>: Producer<Element> {
let source: Observable<Element>
let duration: RxTimeInterval
let scheduler: SchedulerType
init(source: Observable<Element>, duration: RxTimeInterval, scheduler: SchedulerType) {
self.source = source
self.scheduler = scheduler
self.duration = duration
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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 skipUntil<Source: ObservableType>(_ other: Source)
-> Observable<Element> {
return SkipUntil(source: self.asObservable(), other: other.asObservable())
}
}
final private class SkipUntilSinkOther<Other, Observer: ObserverType>
: ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Parent = SkipUntilSink<Other, Observer>
typealias Element = Other
private let _parent: Parent
var _lock: RecursiveLock {
return self._parent._lock
}
let _subscription = SingleAssignmentDisposable()
init(parent: Parent) {
self._parent = parent
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
}
func on(_ event: Event<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
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<Other, Observer: ObserverType>
: Sink<Observer>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = Observer.Element
typealias Parent = SkipUntil<Element, Other>
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<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
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<Element, Other>: Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _other: Observable<Other>
init(source: Observable<Element>, other: Observable<Other>) {
self._source = source
self._other = other
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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 skipWhile(_ predicate: @escaping (Element) throws -> Bool) -> Observable<Element> {
return SkipWhile(source: self.asObservable(), predicate: predicate)
}
}
final private class SkipWhileSink<Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias Element = Observer.Element
typealias Parent = SkipWhile<Element>
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<Element>) {
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<Element>: Producer<Element> {
typealias Predicate = (Element) throws -> Bool
private let _source: Observable<Element>
fileprivate let _predicate: Predicate
init(source: Observable<Element>, predicate: @escaping Predicate) {
self._source = source
self._predicate = predicate
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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<Element> {
return StartWith(source: self.asObservable(), elements: elements)
}
}
final private class StartWith<Element>: Producer<Element> {
let elements: [Element]
let source: Observable<Element>
init(source: Observable<Element>, elements: [Element]) {
self.source = source
self.elements = elements
super.init()
}
override func run<Observer: ObserverType>(_ 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))
}
}
//
// SubjectType.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/1/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// Represents an object that is both an observable sequence as well as an observer.
public protocol SubjectType : ObservableType {
/// The type of the observer that represents this subject.
///
/// Usually this type is type of subject itself, but it doesn't have to be.
associatedtype Observer: ObserverType
@available(*, deprecated, renamed: "Observer")
typealias SubjectObserverType = Observer
/// Returns observer interface for subject.
///
/// - returns: Observer interface for subject.
func asObserver() -> Observer
}
//
// 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 subscribeOn(_ scheduler: ImmediateSchedulerType)
-> Observable<Element> {
return SubscribeOn(source: self, scheduler: scheduler)
}
}
final private class SubscribeOnSink<Ob: ObservableType, Observer: ObserverType>: Sink<Observer>, ObserverType where Ob.Element == Observer.Element {
typealias Element = Observer.Element
typealias Parent = SubscribeOn<Ob>
let parent: Parent
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
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<Ob: ObservableType>: Producer<Ob.Element> {
let source: Ob
let scheduler: ImmediateSchedulerType
init(source: Ob, scheduler: ImmediateSchedulerType) {
self.source = source
self.scheduler = scheduler
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// SubscriptionDisposable.swift
// RxSwift
//
// Created by Krunoslav Zaher on 10/25/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
struct SubscriptionDisposable<T: SynchronizedUnsubscribeType> : 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)
}
}
//
// SwiftSupport.swift
// RxSwift
//
// Created by Volodymyr Gorbenko on 3/6/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
import Foundation
typealias IntMax = Int64
public typealias RxAbstractInteger = FixedWidthInteger
extension SignedInteger {
func toIntMax() -> IntMax {
return IntMax(self)
}
}
//
// 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<Source: ObservableConvertibleType>(_ selector: @escaping (Element) throws -> Source)
-> Observable<Source.Element> {
return FlatMapLatest(source: self.asObservable(), selector: 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<Element.Element> {
return Switch(source: self.asObservable())
}
}
private class SwitchSink<SourceType, Source: ObservableConvertibleType, Observer: ObserverType>
: Sink<Observer>
, 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<SourceType>) -> 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<Source.Element>)? {
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<Element>) {
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, _self: 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<SourceType, Source: ObservableConvertibleType, Observer: ObserverType>
: ObserverType
, LockOwnerType
, SynchronizedOnType where Source.Element == Observer.Element {
typealias Element = Source.Element
typealias Parent = SwitchSink<SourceType, Source, Observer>
private let _parent: Parent
private let _id: Int
private let _self: Disposable
var _lock: RecursiveLock {
return self._parent._lock
}
init(parent: Parent, id: Int, _self: Disposable) {
self._parent = parent
self._id = id
self._self = _self
}
func on(_ event: Event<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
switch event {
case .next: break
case .error, .completed:
self._self.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<Source: ObservableConvertibleType, Observer: ObserverType>: SwitchSink<Source, Source, Observer>
where Observer.Element == Source.Element {
override init(observer: Observer, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
override func performMap(_ element: Source) throws -> Source {
return element
}
}
final private class MapSwitchSink<SourceType, Source: ObservableConvertibleType, Observer: ObserverType>: SwitchSink<SourceType, Source, Observer> 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 {
return try self._selector(element)
}
}
// MARK: Producers
final private class Switch<Source: ObservableConvertibleType>: Producer<Source.Element> {
private let _source: Observable<Source>
init(source: Observable<Source>) {
self._source = source
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Source.Element {
let sink = SwitchIdentitySink<Source, Observer>(observer: observer, cancel: cancel)
let subscription = sink.run(self._source)
return (sink: sink, subscription: subscription)
}
}
final private class FlatMapLatest<SourceType, Source: ObservableConvertibleType>: Producer<Source.Element> {
typealias Selector = (SourceType) throws -> Source
private let _source: Observable<SourceType>
private let _selector: Selector
init(source: Observable<SourceType>, selector: @escaping Selector) {
self._source = source
self._selector = selector
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Source.Element {
let sink = MapSwitchSink<SourceType, Source, Observer>(selector: self._selector, observer: observer, cancel: cancel)
let subscription = sink.run(self._source)
return (sink: sink, subscription: subscription)
}
}
//
// 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 switchTo: 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<Element>) -> Observable<Element> {
return SwitchIfEmpty(source: self.asObservable(), ifEmpty: other)
}
}
final private class SwitchIfEmpty<Element>: Producer<Element> {
private let _source: Observable<Element>
private let _ifEmpty: Observable<Element>
init(source: Observable<Element>, ifEmpty: Observable<Element>) {
self._source = source
self._ifEmpty = ifEmpty
}
override func run<Observer: ObserverType>(_ 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<Observer: ObserverType>: Sink<Observer>
, ObserverType {
typealias Element = Observer.Element
private let _ifEmpty: Observable<Element>
private var _isEmpty = true
private let _ifEmptySubscription = SingleAssignmentDisposable()
init(ifEmpty: Observable<Element>, observer: Observer, cancel: Cancelable) {
self._ifEmpty = ifEmpty
super.init(observer: observer, cancel: cancel)
}
func run(_ source: Observable<Observer.Element>) -> Disposable {
let subscription = source.subscribe(self)
return Disposables.create(subscription, _ifEmptySubscription)
}
func on(_ event: Event<Element>) {
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<Observer: ObserverType>
: ObserverType {
typealias Element = Observer.Element
typealias Parent = SwitchIfEmptySink<Observer>
private let _parent: Parent
init(parent: Parent) {
self._parent = parent
}
func on(_ event: Event<Element>) {
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()
}
}
}
//
// SynchronizedDisposeType.swift
// RxSwift
//
// Created by Krunoslav Zaher on 10/25/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
protocol SynchronizedDisposeType : class, Disposable, Lock {
func _synchronized_dispose()
}
extension SynchronizedDisposeType {
func synchronizedDispose() {
self.lock(); defer { self.unlock() }
self._synchronized_dispose()
}
}
//
// SynchronizedOnType.swift
// RxSwift
//
// Created by Krunoslav Zaher on 10/25/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
protocol SynchronizedOnType : class, ObserverType, Lock {
func _synchronized_on(_ event: Event<Element>)
}
extension SynchronizedOnType {
func synchronizedOn(_ event: Event<Element>) {
self.lock(); defer { self.unlock() }
self._synchronized_on(event)
}
}
//
// SynchronizedUnsubscribeType.swift
// RxSwift
//
// Created by Krunoslav Zaher on 10/25/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
protocol SynchronizedUnsubscribeType : class {
associatedtype DisposeKey
func synchronizedUnsubscribe(_ disposeKey: DisposeKey)
}
//
// 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<Sequence: Swift.Sequence, Observer: ObserverType>
: Sink<Observer>
, 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 _isDisposed = false
var _subscription = SerialDisposable()
// this is thread safe object
var _gate = AsyncLock<InvocableScheduledItem<TailRecursiveSink<Sequence, Observer>>>()
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<Element>) -> SequenceGenerator? {
rxAbstractMethod()
}
// should be done on gate locked
private func moveNextCommand() {
var next: Observable<Element>?
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<Element>) -> Disposable {
rxAbstractMethod()
}
func disposeCommand() {
self._isDisposed = true
self._generators.removeAll(keepingCapacity: false)
}
override func dispose() {
super.dispose()
self._subscription.dispose()
self._gate.dispose()
self.schedule(.dispose)
}
}
//
// 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<Element> {
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(_ duration: RxTimeInterval, scheduler: SchedulerType)
-> Observable<Element> {
return TakeTime(source: self.asObservable(), duration: duration, scheduler: scheduler)
}
}
// count version
final private class TakeCountSink<Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias Element = Observer.Element
typealias Parent = TakeCount<Element>
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<Element>) {
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<Element>: Producer<Element> {
private let _source: Observable<Element>
fileprivate let _count: Int
init(source: Observable<Element>, count: Int) {
if count < 0 {
rxFatalError("count can't be negative")
}
self._source = source
self._count = count
}
override func run<Observer: ObserverType>(_ 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<Element, Observer: ObserverType>
: Sink<Observer>
, LockOwnerType
, ObserverType
, SynchronizedOnType where Observer.Element == Element {
typealias Parent = TakeTime<Element>
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<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
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.lock(); defer { self._lock.unlock() }
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<Element>: Producer<Element> {
typealias TimeInterval = RxTimeInterval
fileprivate let _source: Observable<Element>
fileprivate let _duration: TimeInterval
fileprivate let _scheduler: SchedulerType
init(source: Observable<Element>, duration: TimeInterval, scheduler: SchedulerType) {
self._source = source
self._scheduler = scheduler
self._duration = duration
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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<Element> {
return TakeLast(source: self.asObservable(), count: count)
}
}
final private class TakeLastSink<Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias Element = Observer.Element
typealias Parent = TakeLast<Element>
private let _parent: Parent
private var _elements: Queue<Element>
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self._parent = parent
self._elements = Queue<Element>(capacity: parent._count + 1)
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
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<Element>: Producer<Element> {
private let _source: Observable<Element>
fileprivate let _count: Int
init(source: Observable<Element>, count: Int) {
if count < 0 {
rxFatalError("count can't be negative")
}
self._source = source
self._count = count
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// TakeUntil.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 takeUntil<Source: ObservableType>(_ other: Source)
-> Observable<Element> {
return 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 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.
*/
public func takeUntil(_ behavior: TakeUntilBehavior,
predicate: @escaping (Element) throws -> Bool)
-> Observable<Element> {
return TakeUntilPredicate(source: self.asObservable(),
behavior: behavior,
predicate: predicate)
}
}
/// Behaviors for the `takeUntil(_ behavior:predicate:)` operator.
public enum TakeUntilBehavior {
/// 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<Other, Observer: ObserverType>
: ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Parent = TakeUntilSink<Other, Observer>
typealias Element = Other
private let _parent: Parent
var _lock: RecursiveLock {
return self._parent._lock
}
fileprivate let _subscription = SingleAssignmentDisposable()
init(parent: Parent) {
self._parent = parent
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
}
func on(_ event: Event<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
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<Other, Observer: ObserverType>
: Sink<Observer>
, LockOwnerType
, ObserverType
, SynchronizedOnType {
typealias Element = Observer.Element
typealias Parent = TakeUntil<Element, Other>
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<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
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<Element, Other>: Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _other: Observable<Other>
init(source: Observable<Element>, other: Observable<Other>) {
self._source = source
self._other = other
}
override func run<Observer: ObserverType>(_ 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<Observer: ObserverType>
: Sink<Observer>, ObserverType {
typealias Element = Observer.Element
typealias Parent = TakeUntilPredicate<Element>
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<Element>) {
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<Element>: Producer<Element> {
typealias Predicate = (Element) throws -> Bool
private let _source: Observable<Element>
fileprivate let _predicate: Predicate
fileprivate let _behavior: TakeUntilBehavior
init(source: Observable<Element>,
behavior: TakeUntilBehavior,
predicate: @escaping Predicate) {
self._source = source
self._behavior = behavior
self._predicate = predicate
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// TakeWhile.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/7/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
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 takeWhile(_ predicate: @escaping (Element) throws -> Bool)
-> Observable<Element> {
return TakeWhile(source: self.asObservable(), predicate: predicate)
}
}
final private class TakeWhileSink<Observer: ObserverType>
: Sink<Observer>
, ObserverType {
typealias Element = Observer.Element
typealias Parent = TakeWhile<Element>
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<Element>) {
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 {
self.forwardOn(.completed)
self.dispose()
}
case .error, .completed:
self.forwardOn(event)
self.dispose()
}
}
}
final private class TakeWhile<Element>: Producer<Element> {
typealias Predicate = (Element) throws -> Bool
private let _source: Observable<Element>
fileprivate let _predicate: Predicate
init(source: Observable<Element>, predicate: @escaping Predicate) {
self._source = source
self._predicate = predicate
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = TakeWhileSink(parent: self, observer: observer, cancel: cancel)
let subscription = self._source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
//
// Throttle.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/22/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import struct Foundation.Date
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<Element> {
return Throttle(source: self.asObservable(), dueTime: dueTime, latest: latest, scheduler: scheduler)
}
}
final private class ThrottleSink<Observer: ObserverType>
: Sink<Observer>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = Observer.Element
typealias ParentType = Throttle<Element>
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<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
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.lock(); defer { self._lock.unlock() } // {
if let lastUnsentElement = self._lastUnsentElement {
self.sendNow(element: lastUnsentElement)
}
if self._completed {
self.forwardOn(.completed)
self.dispose()
}
// }
return Disposables.create()
}
}
final private class Throttle<Element>: Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _dueTime: RxTimeInterval
fileprivate let _latest: Bool
fileprivate let _scheduler: SchedulerType
init(source: Observable<Element>, dueTime: RxTimeInterval, latest: Bool, scheduler: SchedulerType) {
self._source = source
self._dueTime = dueTime
self._latest = latest
self._scheduler = scheduler
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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<Element> {
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<Source: ObservableConvertibleType>(_ dueTime: RxTimeInterval, other: Source, scheduler: SchedulerType)
-> Observable<Element> where Element == Source.Element {
return Timeout(source: self.asObservable(), dueTime: dueTime, other: other.asObservable(), scheduler: scheduler)
}
}
final private class TimeoutSink<Observer: ObserverType>: Sink<Observer>, LockOwnerType, ObserverType {
typealias Element = Observer.Element
typealias Parent = Timeout<Element>
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<Element>) {
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<Element>: Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _dueTime: RxTimeInterval
fileprivate let _other: Observable<Element>
fileprivate let _scheduler: SchedulerType
init(source: Observable<Element>, dueTime: RxTimeInterval, other: Observable<Element>, scheduler: SchedulerType) {
self._source = source
self._dueTime = dueTime
self._other = other
self._scheduler = scheduler
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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<Element> {
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<Element> {
return Timer(
dueTime: dueTime,
period: period,
scheduler: scheduler
)
}
}
import Foundation
final private class TimerSink<Observer: ObserverType> : Sink<Observer> where Observer.Element : RxAbstractInteger {
typealias Parent = Timer<Observer.Element>
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.lock(); defer { self._lock.unlock() }
self.forwardOn(.next(state))
return state &+ 1
}
}
}
final private class TimerOneOffSink<Observer: ObserverType>: Sink<Observer> where Observer.Element: RxAbstractInteger {
typealias Parent = Timer<Observer.Element>
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<Element: RxAbstractInteger>: Producer<Element> {
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: ObserverType>(_ 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)
}
}
}
//
// 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]> {
return PrimitiveSequence(raw: ToArray(source: self.asObservable()))
}
}
final private class ToArraySink<SourceType, Observer: ObserverType>: Sink<Observer>, ObserverType where Observer.Element == [SourceType] {
typealias Parent = ToArray<SourceType>
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<SourceType>) {
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<SourceType>: Producer<[SourceType]> {
let _source: Observable<SourceType>
init(source: Observable<SourceType>) {
self._source = source
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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<Resource: Disposable>(_ resourceFactory: @escaping () throws -> Resource, observableFactory: @escaping (Resource) throws -> Observable<Element>) -> Observable<Element> {
return Using(resourceFactory: resourceFactory, observableFactory: observableFactory)
}
}
final private class UsingSink<ResourceType: Disposable, Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias SourceType = Observer.Element
typealias Parent = Using<SourceType, ResourceType>
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<SourceType>) {
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<SourceType, ResourceType: Disposable>: Producer<SourceType> {
typealias Element = SourceType
typealias ResourceFactory = () throws -> ResourceType
typealias ObservableFactory = (ResourceType) throws -> Observable<SourceType>
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: ObserverType>(_ 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)
}
}
//
// 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 `NSTimeInterval`.
- parameter virtualTimeInterval: Virtual time interval to convert to `NSTimeInterval`.
- returns: `NSTimeInterval` corresponding to virtual time interval.
*/
func convertFromVirtualTimeInterval(_ virtualTimeInterval: VirtualTimeIntervalUnit) -> TimeInterval
/**
Converts from `NSTimeInterval` to virtual time interval.
- parameter timeInterval: `NSTimeInterval` 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 {
return self == .lessThan
}
/// lhs > rhs
var greaterThan: Bool {
return self == .greaterThan
}
/// lhs == rhs
var equal: Bool {
return self == .equal
}
}
//
// 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<Converter: VirtualTimeConverterType>
: SchedulerType {
public typealias VirtualTime = Converter.VirtualTimeUnit
public typealias VirtualTimeInterval = Converter.VirtualTimeIntervalUnit
private var _running : Bool
private var _clock: VirtualTime
private var _schedulerQueue : PriorityQueue<VirtualSchedulerItem<VirtualTime>>
private var _converter: Converter
private var _nextId = 0
/// - returns: Current time.
public var now: RxTime {
return self._converter.convertFromVirtualTime(self.clock)
}
/// - returns: Scheduler's absolute time clock value.
public var clock: VirtualTime {
return self._clock
}
/// Creates a new virtual time scheduler.
///
/// - parameter initialClock: Initial value for the clock.
public init(initialClock: VirtualTime, converter: Converter) {
self._clock = 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<StateType>(_ 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<StateType>(_ 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<StateType>(_ 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<StateType>(_ 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 {
return 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._clock = next.time
}
next.invoke()
self._schedulerQueue.remove(next)
} while self._running
self._running = false
}
func findNext() -> VirtualSchedulerItem<VirtualTime>? {
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._clock = next.time
}
next.invoke()
self._schedulerQueue.remove(next)
} while self._running
self._clock = 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._clock = 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 {
return self._schedulerQueue.debugDescription
}
}
final class VirtualSchedulerItem<Time>
: Disposable {
typealias Action = () -> Disposable
let action: Action
let time: Time
let id: Int
var isDisposed: Bool {
return self.disposable.isDisposed
}
var disposable = SingleAssignmentDisposable()
init(action: @escaping Action, time: Time, id: Int) {
self.action = action
self.time = time
self.id = id
}
func invoke() {
self.disposable.setDisposable(self.action())
}
func dispose() {
self.disposable.dispose()
}
}
extension VirtualSchedulerItem
: CustomDebugStringConvertible {
var debugDescription: String {
return "\(self.time)"
}
}
//
// 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<Observable<Element>> {
return WindowTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler)
}
}
final private class WindowTimeCountSink<Element, Observer: ObserverType>
: Sink<Observer>
, ObserverType
, LockOwnerType
, SynchronizedOnType where Observer.Element == Observable<Element> {
typealias Parent = WindowTimeCount<Element>
private let _parent: Parent
let _lock = RecursiveLock()
private var _subject = PublishSubject<Element>()
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<Element>()
self.forwardOn(.next(AddRef(source: self._subject, refCount: self._refCountDisposable).asObservable()))
}
func on(_ event: Event<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
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<Element>: Producer<Observable<Element>> {
fileprivate let _timeSpan: RxTimeInterval
fileprivate let _count: Int
fileprivate let _scheduler: SchedulerType
fileprivate let _source: Observable<Element>
init(source: Observable<Element>, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) {
self._source = source
self._timeSpan = timeSpan
self._count = count
self._scheduler = scheduler
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Observable<Element> {
let sink = WindowTimeCountSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
//
// 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)
- 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<Source: ObservableConvertibleType, ResultType>(_ second: Source, resultSelector: @escaping (Element, Source.Element) throws -> ResultType) -> Observable<ResultType> {
return 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)
- 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<Source: ObservableConvertibleType>(_ second: Source) -> Observable<Source.Element> {
return WithLatestFrom(first: self.asObservable(), second: second.asObservable(), resultSelector: { $1 })
}
}
final private class WithLatestFromSink<FirstType, SecondType, Observer: ObserverType>
: Sink<Observer>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias ResultType = Observer.Element
typealias Parent = WithLatestFrom<FirstType, SecondType, ResultType>
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<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
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<FirstType, SecondType, Observer: ObserverType>
: ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias ResultType = Observer.Element
typealias Parent = WithLatestFromSink<FirstType, SecondType, Observer>
typealias Element = SecondType
private let _parent: Parent
private let _disposable: Disposable
var _lock: RecursiveLock {
return self._parent._lock
}
init(parent: Parent, disposable: Disposable) {
self._parent = parent
self._disposable = disposable
}
func on(_ event: Event<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
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<FirstType, SecondType, ResultType>: Producer<ResultType> {
typealias ResultSelector = (FirstType, SecondType) throws -> ResultType
fileprivate let _first: Observable<FirstType>
fileprivate let _second: Observable<SecondType>
fileprivate let _resultSelector: ResultSelector
init(first: Observable<FirstType>, second: Observable<SecondType>, resultSelector: @escaping ResultSelector) {
self._first = first
self._second = second
self._resultSelector = resultSelector
}
override func run<Observer: ObserverType>(_ 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)
}
}
//
// 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: Swift.Collection>(_ collection: Collection, resultSelector: @escaping ([Collection.Element.Element]) throws -> Element) -> Observable<Element>
where Collection.Element: ObservableType {
return 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: Swift.Collection>(_ collection: Collection) -> Observable<[Element]>
where Collection.Element: ObservableType, Collection.Element.Element == Element {
return ZipCollectionType(sources: collection, resultSelector: { $0 })
}
}
final private class ZipCollectionTypeSink<Collection: Swift.Collection, Observer: ObserverType>
: Sink<Observer> where Collection.Element: ObservableConvertibleType {
typealias Result = Observer.Element
typealias Parent = ZipCollectionType<Collection, Result>
typealias SourceElement = Collection.Element.Element
private let _parent: Parent
private let _lock = RecursiveLock()
// state
private var _numberOfValues = 0
private var _values: [Queue<SourceElement>]
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<SourceElement>](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<SourceElement>, 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<Collection: Swift.Collection, Result>: Producer<Result> 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: ObserverType>(_ 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)
}
}
// 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<O1: ObservableType, O2: ObservableType>
(_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.Element, O2.Element) throws -> Element)
-> Observable<Element> {
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<O1: ObservableType, O2: ObservableType>
(_ source1: O1, _ source2: O2)
-> Observable<(O1.Element, O2.Element)> {
return Zip2(
source1: source1.asObservable(), source2: source2.asObservable(),
resultSelector: { ($0, $1) }
)
}
}
final class ZipSink2_<E1, E2, Observer: ObserverType> : ZipSink<Observer> {
typealias Result = Observer.Element
typealias Parent = Zip2<E1, E2, Result>
let _parent: Parent
var _values1: Queue<E1> = Queue(capacity: 2)
var _values2: Queue<E2> = 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 {
return try self._parent._resultSelector(self._values1.dequeue()!, self._values2.dequeue()!)
}
}
final class Zip2<E1, E2, Result> : Producer<Result> {
typealias ResultSelector = (E1, E2) throws -> Result
let source1: Observable<E1>
let source2: Observable<E2>
let _resultSelector: ResultSelector
init(source1: Observable<E1>, source2: Observable<E2>, resultSelector: @escaping ResultSelector) {
self.source1 = source1
self.source2 = source2
self._resultSelector = resultSelector
}
override func run<Observer: ObserverType>(_ 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<O1: ObservableType, O2: ObservableType, O3: ObservableType>
(_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.Element, O2.Element, O3.Element) throws -> Element)
-> Observable<Element> {
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<O1: ObservableType, O2: ObservableType, O3: ObservableType>
(_ 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_<E1, E2, E3, Observer: ObserverType> : ZipSink<Observer> {
typealias Result = Observer.Element
typealias Parent = Zip3<E1, E2, E3, Result>
let _parent: Parent
var _values1: Queue<E1> = Queue(capacity: 2)
var _values2: Queue<E2> = Queue(capacity: 2)
var _values3: Queue<E3> = 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 {
return try self._parent._resultSelector(self._values1.dequeue()!, self._values2.dequeue()!, self._values3.dequeue()!)
}
}
final class Zip3<E1, E2, E3, Result> : Producer<Result> {
typealias ResultSelector = (E1, E2, E3) throws -> Result
let source1: Observable<E1>
let source2: Observable<E2>
let source3: Observable<E3>
let _resultSelector: ResultSelector
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, resultSelector: @escaping ResultSelector) {
self.source1 = source1
self.source2 = source2
self.source3 = source3
self._resultSelector = resultSelector
}
override func run<Observer: ObserverType>(_ 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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType>
(_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element) throws -> Element)
-> Observable<Element> {
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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType>
(_ 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_<E1, E2, E3, E4, Observer: ObserverType> : ZipSink<Observer> {
typealias Result = Observer.Element
typealias Parent = Zip4<E1, E2, E3, E4, Result>
let _parent: Parent
var _values1: Queue<E1> = Queue(capacity: 2)
var _values2: Queue<E2> = Queue(capacity: 2)
var _values3: Queue<E3> = Queue(capacity: 2)
var _values4: Queue<E4> = 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 {
return try self._parent._resultSelector(self._values1.dequeue()!, self._values2.dequeue()!, self._values3.dequeue()!, self._values4.dequeue()!)
}
}
final class Zip4<E1, E2, E3, E4, Result> : Producer<Result> {
typealias ResultSelector = (E1, E2, E3, E4) throws -> Result
let source1: Observable<E1>
let source2: Observable<E2>
let source3: Observable<E3>
let source4: Observable<E4>
let _resultSelector: ResultSelector
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, source4: Observable<E4>, resultSelector: @escaping ResultSelector) {
self.source1 = source1
self.source2 = source2
self.source3 = source3
self.source4 = source4
self._resultSelector = resultSelector
}
override func run<Observer: ObserverType>(_ 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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType>
(_ 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<Element> {
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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType>
(_ 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_<E1, E2, E3, E4, E5, Observer: ObserverType> : ZipSink<Observer> {
typealias Result = Observer.Element
typealias Parent = Zip5<E1, E2, E3, E4, E5, Result>
let _parent: Parent
var _values1: Queue<E1> = Queue(capacity: 2)
var _values2: Queue<E2> = Queue(capacity: 2)
var _values3: Queue<E3> = Queue(capacity: 2)
var _values4: Queue<E4> = Queue(capacity: 2)
var _values5: Queue<E5> = 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 {
return try self._parent._resultSelector(self._values1.dequeue()!, self._values2.dequeue()!, self._values3.dequeue()!, self._values4.dequeue()!, self._values5.dequeue()!)
}
}
final class Zip5<E1, E2, E3, E4, E5, Result> : Producer<Result> {
typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> Result
let source1: Observable<E1>
let source2: Observable<E2>
let source3: Observable<E3>
let source4: Observable<E4>
let source5: Observable<E5>
let _resultSelector: ResultSelector
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, source4: Observable<E4>, source5: Observable<E5>, 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: ObserverType>(_ 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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType, O6: ObservableType>
(_ 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<Element> {
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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType, O6: ObservableType>
(_ 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_<E1, E2, E3, E4, E5, E6, Observer: ObserverType> : ZipSink<Observer> {
typealias Result = Observer.Element
typealias Parent = Zip6<E1, E2, E3, E4, E5, E6, Result>
let _parent: Parent
var _values1: Queue<E1> = Queue(capacity: 2)
var _values2: Queue<E2> = Queue(capacity: 2)
var _values3: Queue<E3> = Queue(capacity: 2)
var _values4: Queue<E4> = Queue(capacity: 2)
var _values5: Queue<E5> = Queue(capacity: 2)
var _values6: Queue<E6> = 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 {
return 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<E1, E2, E3, E4, E5, E6, Result> : Producer<Result> {
typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> Result
let source1: Observable<E1>
let source2: Observable<E2>
let source3: Observable<E3>
let source4: Observable<E4>
let source5: Observable<E5>
let source6: Observable<E6>
let _resultSelector: ResultSelector
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, source4: Observable<E4>, source5: Observable<E5>, source6: Observable<E6>, 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: ObserverType>(_ 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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType, O6: ObservableType, O7: ObservableType>
(_ 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<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: 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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType, O6: ObservableType, O7: ObservableType>
(_ 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_<E1, E2, E3, E4, E5, E6, E7, Observer: ObserverType> : ZipSink<Observer> {
typealias Result = Observer.Element
typealias Parent = Zip7<E1, E2, E3, E4, E5, E6, E7, Result>
let _parent: Parent
var _values1: Queue<E1> = Queue(capacity: 2)
var _values2: Queue<E2> = Queue(capacity: 2)
var _values3: Queue<E3> = Queue(capacity: 2)
var _values4: Queue<E4> = Queue(capacity: 2)
var _values5: Queue<E5> = Queue(capacity: 2)
var _values6: Queue<E6> = Queue(capacity: 2)
var _values7: Queue<E7> = 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 {
return 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<E1, E2, E3, E4, E5, E6, E7, Result> : Producer<Result> {
typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> Result
let source1: Observable<E1>
let source2: Observable<E2>
let source3: Observable<E3>
let source4: Observable<E4>
let source5: Observable<E5>
let source6: Observable<E6>
let source7: Observable<E7>
let _resultSelector: ResultSelector
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, source4: Observable<E4>, source5: Observable<E5>, source6: Observable<E6>, source7: Observable<E7>, 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: ObserverType>(_ 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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType, O6: ObservableType, O7: ObservableType, O8: ObservableType>
(_ 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<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: 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<O1: ObservableType, O2: ObservableType, O3: ObservableType, O4: ObservableType, O5: ObservableType, O6: ObservableType, O7: ObservableType, O8: ObservableType>
(_ 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_<E1, E2, E3, E4, E5, E6, E7, E8, Observer: ObserverType> : ZipSink<Observer> {
typealias Result = Observer.Element
typealias Parent = Zip8<E1, E2, E3, E4, E5, E6, E7, E8, Result>
let _parent: Parent
var _values1: Queue<E1> = Queue(capacity: 2)
var _values2: Queue<E2> = Queue(capacity: 2)
var _values3: Queue<E3> = Queue(capacity: 2)
var _values4: Queue<E4> = Queue(capacity: 2)
var _values5: Queue<E5> = Queue(capacity: 2)
var _values6: Queue<E6> = Queue(capacity: 2)
var _values7: Queue<E7> = Queue(capacity: 2)
var _values8: Queue<E8> = 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 {
return 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<E1, E2, E3, E4, E5, E6, E7, E8, Result> : Producer<Result> {
typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> Result
let source1: Observable<E1>
let source2: Observable<E2>
let source3: Observable<E3>
let source4: Observable<E4>
let source5: Observable<E5>
let source6: Observable<E6>
let source7: Observable<E7>
let source8: Observable<E8>
let _resultSelector: ResultSelector
init(source1: Observable<E1>, source2: Observable<E2>, source3: Observable<E3>, source4: Observable<E4>, source5: Observable<E5>, source6: Observable<E6>, source7: Observable<E7>, source8: Observable<E8>, 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: ObserverType>(_ 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)
}
}
//
// Zip.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/23/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
protocol ZipSinkProtocol : class
{
func next(_ index: Int)
func fail(_ error: Swift.Error)
func done(_ index: Int)
}
class ZipSink<Observer: ObserverType> : Sink<Observer>, 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<Element>
: 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<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
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)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment