ronantakizawa/codereview-bench huggingface dataset:
Repository: ReactiveX/RxSwift
File: Tests/RxSwiftTests/MaybeTest.swift (Swift)

Code before:
            completed(200)
            ])
    }

    func test_ifEmptySwitchToMaybe() {
        let scheduler = TestScheduler(initialClock: 0)
        let source = Maybe<Int>.empty()
        let switchSource = Maybe.just(10)

        let res = scheduler.start {
            (source.ifEmpty(switchTo: switchSource).asObservable())
        }

        XCTAssertEqual(res.events, [
            next(200, 10),
            completed(200)
            ])
    }

    func test_ifEmptySwitchToSingle() {
        let scheduler = TestScheduler(initialClock: 0)
        let source = Maybe<Int>.empty()
        let switchSource = Single.just(10)

        let res = scheduler.start {
            (source.ifEmpty(switchTo: switchSource).asObservable())
        }

        XCTAssertEqual(res.events, [
            next(200, 10),
            completed(200)
            ])
    }
}

extension MaybeTest {
    func test_zip_tuple() {
        let scheduler = TestScheduler(initialClock: 0)

        let res = scheduler.start {
            (Maybe.zip(Maybe.just(1), Maybe.just(2)) as Maybe<(Int, Int)>).map { $0.0 + $0.1 }.asObservable()
        }

        XCTAssertEqual(res.events, [
            next(200, 3),
            completed(200)
            ])
    }

    func test_zip_resultSelector() {
        let scheduler = TestScheduler(initialClock: 0)

Review comment (suggestion):
```
(Maybe<Int>.empty().ifEmpty(switchTo: Single.just(10)) as Single<Int>).asObservable()
```

Code after:
            completed(200)
            ])
    }

    func test_ifEmptySwitchToMaybe() {
        let scheduler = TestScheduler(initialClock: 0)
        let source = Maybe<Int>.empty()
        let switchSource = Maybe.just(10)

        let res = scheduler.start {
            ((source.ifEmpty(switchTo: switchSource) as Maybe<Int>).asObservable())
        }

        XCTAssertEqual(res.events, [
            next(200, 10),
            completed(200)
            ])
    }

    func test_ifEmptySwitchToSingle() {
        let scheduler = TestScheduler(initialClock: 0)
        let source = Maybe<Int>.empty()
        let switchSource = Single.just(10)

        let res = scheduler.start {
            ((source.ifEmpty(switchTo: switchSource) as Single<Int>).asObservable())
        }

        XCTAssertEqual(res.events, [
            next(200, 10),
            completed(200)
            ])
    }
}

extension MaybeTest {
    func test_zip_tuple() {
        let scheduler = TestScheduler(initialClock: 0)

        let res = scheduler.start {
            (Maybe.zip(Maybe.just(1), Maybe.just(2)) as Maybe<(Int, Int)>).map { $0.0 + $0.1 }.asObservable()
        }

        XCTAssertEqual(res.events, [
            .next(200, 3),
            .completed(200)
            ])
    }

    func test_zip_resultSelector() {
        let scheduler = TestScheduler(initialClock: 0)
Repository: ReactiveX/RxSwift
File: Platform/DeprecationWarner.swift (Swift)

Code before:
//

import Foundation

#if DEBUG
    class DeprecationWarner {
        private static var warned = [Kind]()
        private static var _lock = NSRecursiveLock()
        
        static func warnIfNeeded(_ kind: Kind) {
            _lock.lock(); defer { _lock.unlock() }
            guard !warned.contains(kind) else { return }
            
            warned.append(kind)
            print("ℹ️ [DEPRECATED] \(kind.message)")
        }
    }
    
    extension DeprecationWarner {
        enum Kind {
            case variable
            case globalTestFunction(String)
            
            var message: String {
                switch self {
                case .variable: return "`Variable` is planned for future deprecation. Please consider `RxCocoa.BehaviorRelay` as a replacement. Read more at: https://git.io/vNqvx"
                case .globalTestFunction(let name): return "The `\(name)()` global function is planned for future deprecation. Please use `Recorded.\(name)()` instead."
                }
            }
        }
    }
    
    extension DeprecationWarner.Kind: Equatable {}
    func ==(lhs: DeprecationWarner.Kind, rhs: DeprecationWarner.Kind) -> Bool {
        switch (lhs, rhs) {
        case (.variable, .variable): return true
        case let (.globalTestFunction(name1), .globalTestFunction(name2)): return name1 == name2
        default: return false
        }
    }
#endif



Review comment (suggestion):
We can remove the specificity of `RxCocoa.BehaviorRelay` as just `BehaviorRelay` and then figure it out as we move towards the next major version

Code after:
//

import Foundation

#if DEBUG
    class DeprecationWarner {
        private static var warned = Set<Kind>()
        private static var _lock = NSRecursiveLock()
        
        static func warnIfNeeded(_ kind: Kind) {
            _lock.lock(); defer { _lock.unlock() }
            guard !warned.contains(kind) else { return }
            
            warned.insert(kind)
            print("ℹ️ [DEPRECATED] \(kind.message)")
        }
    }
    
    extension DeprecationWarner {
        enum Kind {
            case variable
            case globalTestFunctionNext
            case globalTestFunctionError
            case globalTestFunctionCompleted
            
            var message: String {
                switch self {
                case .variable: return "`Variable` is planned for future deprecation. Please consider `BehaviorRelay` as a replacement. Read more at: https://git.io/vNqvx"
                case .globalTestFunctionNext: return "The `next()` global function is planned for future deprecation. Please use `Recorded.next()` instead."
                case .globalTestFunctionError: return "The `error()` global function is planned for future deprecation. Please use `Recorded.error()` instead."
                case .globalTestFunctionCompleted: return "The `completed()` global function is planned for future deprecation. Please use `Recorded.completed()` instead."
                }
            }
        }
    }
#endif
Repository: ReactiveX/RxSwift
File: RxSwift/Traits/Single.swift (Swift)

Code before:

    /**
     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: ElementType)
        -> PrimitiveSequence<TraitType, ElementType> {
        return PrimitiveSequence(raw: primitiveSequence.source.catchErrorJustReturn(element))
    }

    /// Converts `self` to `Maybe` trait.
    ///
    /// - returns: Maybe trait that represents `self`.
    public func asMaybe() -> Maybe<ElementType> {
        return Maybe(raw: primitiveSequence.source)
    }

    /// Converts `self` to `Completable` trait.
    ///
    /// - returns: Completable trait that represents `self`.
    public func asCompletable() -> Completable {
        return Completable.create { completable -> Disposable in
            return self.subscribe(onSuccess: { _ in
                completable(.completed)
            }, onError: { error in
                completable(.error(error))
            })
        }
    }
}


Review comment (suggestion):
Wouldn't it be better to just possibly use `ignoreElements()` ? 

I don't love the idea of subscribing inside a creation-block and using a side effect-ish kind of approach to feeding the completable.

Code after:

    /**
     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: ElementType)
        -> PrimitiveSequence<TraitType, ElementType> {
        return PrimitiveSequence(raw: primitiveSequence.source.catchErrorJustReturn(element))
    }

    /// Converts `self` to `Maybe` trait.
    ///
    /// - returns: Maybe trait that represents `self`.
    public func asMaybe() -> Maybe<ElementType> {
        return Maybe(raw: primitiveSequence.source)
    }

    /// Converts `self` to `Completable` trait.
    ///
    /// - returns: Completable trait that represents `self`.
    public func asCompletable() -> Completable {
        return primitiveSequence.source.ignoreElements()
    }
}
Repository: ReactiveX/RxSwift
File: RxSwift/Disposables/DisposeBag.swift (Swift)

Code before:

        for disposable in oldDisposables {
            disposable.dispose()
        }
    }

    private func _dispose() -> [Disposable] {
        _lock.lock(); defer { _lock.unlock() }

        let disposables = _disposables
        
        _disposables.removeAll(keepingCapacity: false)
        _isDisposed = true
        
        return disposables
    }
    
    deinit {
        dispose()
    }
}

extension DisposeBag {
    /// Convenience function allows a list of disposables to be gathered for disposal.
    ///
    /// With disposeBag.bag:
    /// ```
    /// disposeBag.bag(
    ///     model.name.bind(to: nameLabel),
    ///     model.email.bind(to: emailLabel),
    ///     model.phone.bind(to: phoneLabel)
    /// )
    /// ```
    /// Traditional method without disposeBag.bag:
    /// ```
    ///     model.name.bind(to: nameLabel).disposed(by: disposeBag)
    ///     model.email.bind(to: emailLabel).disposed(by: disposeBag)
    ///     model.phone.bind(to: phoneLabel).disposed(by: disposeBag)
    /// ```
    /// - parameter disposables: List of disposables to add.
    public func bag(_ disposables: Disposable...) {
        _lock.lock(); defer { _lock.unlock() }
        if _isDisposed {
            disposables.forEach { $0.dispose() }
        } else {
            _disposables += disposables
        }
    }
}


Review comment (refactor):
I would remove this explanation and just leave
```
Convenience function allows a list of disposables to be gathered for disposal.

/// - parameter disposables: List of disposables to add.
```

This is a pretty simple API.

Code after:

        for disposable in oldDisposables {
            disposable.dispose()
        }
    }

    private func _dispose() -> [Disposable] {
        _lock.lock(); defer { _lock.unlock() }

        let disposables = _disposables
        
        _disposables.removeAll(keepingCapacity: false)
        _isDisposed = true
        
        return disposables
    }
    
    deinit {
        dispose()
    }
}

extension DisposeBag {

    /// Convenience init allows a list of disposables to be gathered for disposal.
    public convenience init(disposing disposables: Disposable...) {
        self.init()
        _disposables += disposables
    }

    /// Convenience init allows an array of disposables to be gathered for disposal.
    public convenience init(disposing disposables: [Disposable]) {
        self.init()
        _disposables += disposables
    }

    /// Convenience function allows a list of disposables to be gathered for disposal.
    public func insert(_ disposables: Disposable...) {
        insert(disposables)
    }

    /// Convenience function allows an array of disposables to be gathered for disposal.
    public func insert(_ disposables: [Disposable]) {
        _lock.lock(); defer { _lock.unlock() }
        if _isDisposed {
            disposables.forEach { $0.dispose() }
        } else {
            _disposables += disposables
        }
    }
}
Repository: ReactiveX/RxSwift
File: RxSwift/Disposables/DisposeBag.swift (Swift)

Code before:
        let disposables = _disposables
        
        _disposables.removeAll(keepingCapacity: false)
        _isDisposed = true
        
        return disposables
    }
    
    deinit {
        dispose()
    }
}

extension DisposeBag {
    /// Convenience function allows a list of disposables to be gathered for disposal.
    public func insert(_ disposables: Disposable...) {
        _lock.lock(); defer { _lock.unlock() }
        if _isDisposed {
            disposables.forEach { $0.dispose() }
        } else {
            _disposables += disposables
        }
    }

    /// Convenience function allows an array of disposables to be gathered for disposal.
    public func insert(_ disposables: [Disposable]) {
        _lock.lock(); defer { _lock.unlock() }
        if _isDisposed {
            disposables.forEach { $0.dispose() }
        } else {
            _disposables += disposables
        }
    }
}


Review comment (refactor):
DRY - No reason to "rewrite" this method twice. You can use the splatted/variadic version, and pass it down to this method IMO 

Code after:
        let disposables = _disposables
        
        _disposables.removeAll(keepingCapacity: false)
        _isDisposed = true
        
        return disposables
    }
    
    deinit {
        dispose()
    }
}

extension DisposeBag {

    /// Convenience init allows a list of disposables to be gathered for disposal.
    public convenience init(disposing disposables: Disposable...) {
        self.init()
        _disposables += disposables
    }

    /// Convenience init allows an array of disposables to be gathered for disposal.
    public convenience init(disposing disposables: [Disposable]) {
        self.init()
        _disposables += disposables
    }

    /// Convenience function allows a list of disposables to be gathered for disposal.
    public func insert(_ disposables: Disposable...) {
        insert(disposables)
    }

    /// Convenience function allows an array of disposables to be gathered for disposal.
    public func insert(_ disposables: [Disposable]) {
        _lock.lock(); defer { _lock.unlock() }
        if _isDisposed {
            disposables.forEach { $0.dispose() }
        } else {
            _disposables += disposables
        }
    }
}
Repository: ReactiveX/RxSwift
File: RxSwift/ObservableType+Extensions.swift (Swift)

Code before:
            let serializedCallStack = subscriptionCallStack.joined(separator: "\n")
            print("Unhandled error happened: \(error)\n subscription called from:\n\(serializedCallStack)")
        #endif
    }
    fileprivate static var _subscriptionCallstackGenerationHandler: SubscriptionCallstackGenerationHandler = {
        #if DEBUG
            return Hooks.recordCallStackOnError ? 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 handler to fetch custom callstack information.
    public static var subscriptionCallstackGenerationHandler: SubscriptionCallstackGenerationHandler {
        get {
            _subscriptionCallstackLock.lock(); defer { _subscriptionCallstackLock.unlock() }
            return _subscriptionCallstackGenerationHandler
        }
        set {
            _subscriptionCallstackLock.lock(); defer { _subscriptionCallstackLock.unlock() }
            _subscriptionCallstackGenerationHandler = newValue
        }
    }
}



Review comment (suggestion):
I would probably rename this into something like `customCaptureSubscriptionCallstack`.

Code after:
            print("Unhandled error happened: \(error)\n subscription called from:\n\(serializedCallStack)")
        #endif
    }
    fileprivate 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
        }
    }
}
Repository: ReactiveX/RxSwift
File: Tests/RxSwiftTests/Observable+PrimitiveSequenceTest.swift (Swift)

Code before:
            completed(210)
            ])
        
        XCTAssertEqual(xs.subscriptions, [
            Subscription(200, 210)
            ])
    }
    
    func testFirst_ManyWithoutCompletion() {
        let scheduler = TestScheduler(initialClock: 0)
        
        let xs = scheduler.createHotObservable([
            next(150, 1),
            next(160, 2),
            next(280, 3),
            next(250, 4),
            next(300, 5)
            ])
        
        let res = scheduler.start { () -> Observable<Int> in
            let single: Single<Int> = xs.first().map { $0 ?? -1 }
            return single.asObservable()
        }
        
        XCTAssertEqual(res.events, [
            next(250, 4),
            completed(250)
            ])
        
        XCTAssertEqual(xs.subscriptions, [
            Subscription(200, 250)
            ])
    }
    
    func testFirst_Error() {
        let scheduler = TestScheduler(initialClock: 0)
        
        let xs = scheduler.createHotObservable([
            next(150, 1),
            error(210, testError)
            ])
        
        let res = scheduler.start { () -> Observable<Int> in
            let single: Single<Int> = xs.first().map { $0 ?? -1 }
            return single.asObservable()
        }
        
        XCTAssertEqual(res.events, [
            error(210, testError)
            ])
        

Review comment (suggestion):
These should all use the static method variation, e.g. 

```suggestion
            .next(250, 4),
```

Code after:
            .completed(210)
            ])
        
        XCTAssertEqual(xs.subscriptions, [
            Subscription(200, 210)
            ])
    }
    
    func testFirst_ManyWithoutCompletion() {
        let scheduler = TestScheduler(initialClock: 0)
        
        let xs = scheduler.createHotObservable([
            .next(150, 1),
            .next(160, 2),
            .next(280, 3),
            .next(250, 4),
            .next(300, 5)
            ])
        
        let res = scheduler.start { () -> Observable<Int> in
            let single: Single<Int> = xs.first().map { $0 ?? -1 }
            return single.asObservable()
        }
        
        XCTAssertEqual(res.events, [
            .next(250, 4),
            .completed(250)
            ])
        
        XCTAssertEqual(xs.subscriptions, [
            Subscription(200, 250)
            ])
    }
    
    func testFirst_Error() {
        let scheduler = TestScheduler(initialClock: 0)
        
        let xs = scheduler.createHotObservable([
            .next(150, 1),
            .error(210, testError)
            ])
        
        let res = scheduler.start { () -> Observable<Int> in
            let single: Single<Int> = xs.first().map { $0 ?? -1 }
            return single.asObservable()
        }
        
        XCTAssertEqual(res.events, [
            .error(210, testError)
            ])
Repository: ReactiveX/RxSwift
File: RxSwift/Observables/ToArray.swift (Swift)

Code before:
//
//  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<[E]> {
        return ToArray(source: self.asObservable()).asSingle()
    }
}

final private class ToArraySink<SourceType, O: ObserverType>: Sink<O>, ObserverType where O.E == [SourceType] {
    typealias Parent = ToArray<SourceType>
    
    let _parent: Parent
    var _list = [SourceType]()
    
    init(parent: Parent, observer: O, 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)

Review comment (suggestion):
Basically I think you can change this one to:

```suggestion
        return PrimitiveSequence(raw: self.asObservable())
```

And it'd be good to go

Code after:
//
//  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<[E]> {
        return PrimitiveSequence(raw: ToArray(source: self.asObservable()))
    }
}

final private class ToArraySink<SourceType, O: ObserverType>: Sink<O>, ObserverType where O.E == [SourceType] {
    typealias Parent = ToArray<SourceType>
    
    let _parent: Parent
    var _list = [SourceType]()
    
    init(parent: Parent, observer: O, 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)