Closure or dynamic protocol implementation?

This might seem like a question about RxSwift, but it really is about
either closures and/or protocols.

Let's say that rxCache.get() returns an Observable. Observable has
a method called subscribe.

let getSub = try rxCache.get(key: 1)
  .subscribe(onNext: { value in
                 XCTAssertNotNil(value)
                 XCTAssertEqual(self.characters[0], value!)
                 onNextCalled = true
                 sem.signal()
             })

subscribe is defined in RxSwift as

public func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
    rxAbstractMethod()
}

public protocol ObserverType {
    /// The type of elements in sequence that observer can observe.
    associatedtype E

    /// Notify observer about sequence event.
    ///
    /// - parameter event: Event that occurred.
    func on(_ event: Event<E>)
}

/// Convenience API extensions to provide alternate next, error, completed events
extension ObserverType {
    
    /// Convenience method equivalent to `on(.next(element: E))`
    ///
    /// - parameter element: Next element to send to observer(s)
    public func onNext(_ element: E) {
        on(.next(element))
    }
    
    /// Convenience method equivalent to `on(.completed)`
    public func onCompleted() {
        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) {
        on(.error(error))
    }
}

Q.1: in the call to subscribe, is the argument a closure? If so, how?
I though closures could only be a single function, and this looks like
it's an implementation of ObserverType?

Q.2: I would like to pass to subscribe an instance that conforms to
ObserverType and implements all three of its methods. What is the
syntax for doing that?

I marked this topic as #off-topic because it‘s a question about RxSwift in general.


Other than that, you‘re looking at the wrong subscribe method, there are multiple.

Check this one out:

There is no magic here, just a different subscribe method that can take multiple closures.

Regarding the second question check out the implementation for AnyObserver.

Then it‘s just ˋobservable.subscribe(yourObserver)ˋ.

1 Like