ronantakizawa/codereview-bench huggingface dataset:
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 PrimitiveSequence(raw: 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)

Review comment (suggestion):
That's not what I wrote :) This should be 

```suggestion
        return PrimitiveSequence(raw: ToArray(source: self.asObservable()))
```

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)
Repository: ReactiveX/RxSwift
File: Tests/RxSwiftTests/Observable+CompactMapTests.swift (Swift)

Code before:
            .next(340, 5),
            .next(380, 6),
            .next(390, 7),
            .next(450, 8),
            .next(470, 9),
            .next(560, 10),
            .next(580, 11),
            .completed(600)
            ])
        
        XCTAssertEqual(xs.subscriptions, [
            Subscription(200, 600)
            ])
        
        XCTAssertEqual(9, invoked)
    }
   
    func test_compactMapNil() {
        let scheduler = TestScheduler(initialClock: 0)
        
        var invoked = 0
        
        let xs = scheduler.createHotObservable([
            .next(110, 1),
            .next(180, 2),
            .next(230, 3),
            .next(270, 4),
            .next(340, 5),
            .next(380, 6),
            .next(390, 7),
            .next(450, 8),
            .next(470, 9),
            .next(560, 10),
            .next(580, 11),
            .completed(600)
            ])
        
        let res = scheduler.start { () -> Observable<Int> in
            return xs.compactMap { _ in
                invoked += 1
                return nil
            }
        }
        
        XCTAssertEqual(res.events, [
            .completed(600)
            ])
        
        XCTAssertEqual(xs.subscriptions, [
            Subscription(200, 600)
            ])

Review comment (suggestion):
Can we add a for an Optional stream, e.g. the "common" usecase of `compactMap`

Code after:

        XCTAssertEqual(xs.subscriptions, [
            Subscription(200, 400)
            ])

        XCTAssertEqual(3, invoked)
    }

    func test_compactMapDisposed() {
        let scheduler = TestScheduler(initialClock: 0)
        
        var invoked = 0
        
        let xs = scheduler.createHotObservable([
            .next(110, 1),
            .next(180, 2),
            .next(230, 3),
            .next(270, 4),
            .next(340, 5),
            .next(380, 6),
            .next(390, 7),
            .next(450, 8),
            .next(470, 9),
            .next(560, 10),
            .next(580, 11),
            .completed(600)
            ])
        
        let res = scheduler.start(disposed: 400) { () -> Observable<Int> in
            return xs.compactMap { num in
                invoked += 1
                return isPrime(num) ? num : nil
            }
        }
        
        XCTAssertEqual(res.events, [
            .next(230, 3),
            .next(340, 5),
            .next(390, 7)
            ])
        
        XCTAssertEqual(xs.subscriptions, [
            Subscription(200, 400)
            ])
        
        XCTAssertEqual(5, invoked)
    }

}
Repository: ReactiveX/RxSwift
File: RxCocoa/iOS/UIApplication+Rx.swift (Swift)

Code before:
//
//  UIApplication+Rx.swift
//  RxCocoa
//
//  Created by Mads Bøgeskov on 18/01/16.
//  Copyright © 2016 Krunoslav Zaher. All rights reserved.
//

#if os(iOS)

import UIKit
import RxSwift

extension Reactive where Base: UIApplication {
    
    /// Bindable sink for `networkActivityIndicatorVisible`.
    public var isNetworkActivityIndicatorVisible: Binder<Bool> {
        return Binder(self.base) { application, active in
            application.isNetworkActivityIndicatorVisible = active
        }
    }
    
    /// Reactive wrapper for `UIApplication.didEnterBackgroundNotification`
    public static var didEnterBackground: ControlEvent<Void> {
        let source = NotificationCenter.default.rx.notification(UIApplication.didEnterBackgroundNotification).map { _ in }
        
        return ControlEvent(events: source)
    }
    
    /// Reactive wrapper for `UIApplication.willEnterForegroundNotification`
    public static var willEnterForeground: ControlEvent<Void> {
        let source = NotificationCenter.default.rx.notification(UIApplication.willEnterForegroundNotification).map { _ in }
        
        return ControlEvent(events: source)
    }
    
    /// Reactive wrapper for `UIApplication.didFinishLaunchingNotification`
    public static var didFinishLaunching: ControlEvent<Void> {
        let source = NotificationCenter.default.rx.notification(UIApplication.didFinishLaunchingNotification).map { _ in }
        
        return ControlEvent(events: source)

Review comment (suggestion):
```suggestion
    /// Bindable sink for `isNetworkActivityIndicatorVisible`.
```

Code after:
//
//  UIApplication+Rx.swift
//  RxCocoa
//
//  Created by Mads Bøgeskov on 18/01/16.
//  Copyright © 2016 Krunoslav Zaher. All rights reserved.
//

#if os(iOS)

import UIKit
import RxSwift

extension Reactive where Base: UIApplication {
    /// Bindable sink for `isNetworkActivityIndicatorVisible`.
    public var isNetworkActivityIndicatorVisible: Binder<Bool> {
        return Binder(self.base) { application, active in
            application.isNetworkActivityIndicatorVisible = active
        }
    }
    
    /// Reactive wrapper for `UIApplication.didEnterBackgroundNotification`
    public static var didEnterBackground: ControlEvent<Void> {
        let source = NotificationCenter.default.rx.notification(UIApplication.didEnterBackgroundNotification).map { _ in }
        
        return ControlEvent(events: source)
    }
    
    /// Reactive wrapper for `UIApplication.willEnterForegroundNotification`
    public static var willEnterForeground: ControlEvent<Void> {
        let source = NotificationCenter.default.rx.notification(UIApplication.willEnterForegroundNotification).map { _ in }
        
        return ControlEvent(events: source)
    }
    
    /// Reactive wrapper for `UIApplication.didFinishLaunchingNotification`
    public static var didFinishLaunching: ControlEvent<Void> {
        let source = NotificationCenter.default.rx.notification(UIApplication.didFinishLaunchingNotification).map { _ in }
        
        return ControlEvent(events: source)
    }
Repository: ReactiveX/RxSwift
File: RxCocoa/iOS/WKWebView+Rx.swift (Swift)

Code before:
    }
    
    /// Reactive wrapper for `navigationDelegate` message.
    public var didStartLoad: Observable<WKNavigation> {
        navigationDelegate
            .methodInvoked(#selector(WKNavigationDelegate.webView(_:didStartProvisionalNavigation:)))
            .map { a in try castOrThrow(WKNavigation.self, a[1]) }
    }

    /// Reactive wrapper for `navigationDelegate` message.
    public var didFinishLoad: Observable<WKNavigation> {
        navigationDelegate
            .methodInvoked(#selector(WKNavigationDelegate.webView(_:didFinish:)))
            .map { a in try castOrThrow(WKNavigation.self, a[1]) }
    }

    /// Reactive wrapper for `navigationDelegate` message.
    public var didFailLoad: Observable<(WKNavigation, Error)> {
        navigationDelegate
            .methodInvoked(#selector(WKNavigationDelegate.webView(_:didFail:withError:)))
            .map { a in
                (
                    try castOrThrow(WKNavigation.self, a[1]),
                    try castOrThrow(Error.self, a[2])
                )
        }
    }
}

#endif


Review comment (suggestion):
Keep curly braces aligned to opening please

```suggestion
            }
```

Code after:
    
    /// Reactive wrapper for `navigationDelegate` message.
    public var didStartLoad: Observable<WKNavigation> {
        navigationDelegate
            .methodInvoked(#selector(WKNavigationDelegate.webView(_:didStartProvisionalNavigation:)))
            .map { a in try castOrThrow(WKNavigation.self, a[1]) }
    }

    /// Reactive wrapper for `navigationDelegate` message.
    public var didFinishLoad: Observable<WKNavigation> {
        navigationDelegate
            .methodInvoked(#selector(WKNavigationDelegate.webView(_:didFinish:)))
            .map { a in try castOrThrow(WKNavigation.self, a[1]) }
    }

    /// Reactive wrapper for `navigationDelegate` message.
    public var didFailLoad: Observable<(WKNavigation, Error)> {
        navigationDelegate
            .methodInvoked(#selector(WKNavigationDelegate.webView(_:didFail:withError:)))
            .map { a in
                (
                    try castOrThrow(WKNavigation.self, a[1]),
                    try castOrThrow(Error.self, a[2])
                )
            }
    }
}

#endif
Repository: ReactiveX/RxSwift
File: Tests/RxCocoaTests/WKWebView+RxTests.swift (Swift)

Code before:
//
//  WKWebView+RxTests.swift
//  Tests
//
//  Created by Giuseppe Lanza on 14/02/2020.
//  Copyright © 2020 Krunoslav Zaher. All rights reserved.
//

#if os(iOS) || os(macOS)

import WebKit
import RxCocoa
import RxSwift
import RxBlocking
import XCTest

// Any WKNavigation object manually created on dealloc crashes the program.
// This class overrides the deinit method of the WKNavition to avoid crashes.
@available(iOS 10.0, OSXApplicationExtension 10.10, *)
private class SafeWKNavigation: WKNavigation {
    static func toggleSafeDealloc() {
        guard let current_original = class_getInstanceMethod(SafeWKNavigation.self, NSSelectorFromString("dealloc")),
            let current_swizzled = class_getInstanceMethod(SafeWKNavigation.self, #selector(nonCrashingDealloc)) else { return }
        method_exchangeImplementations(current_original, current_swizzled)
    }
    
    @objc func nonCrashingDealloc() { }
}

extension String: Error {}

@available(iOS 10.0, OSXApplicationExtension 10.10, *)
final class WKWebViewTests: RxTest {
    
    override func setUp() {
        super.setUp()
        SafeWKNavigation.toggleSafeDealloc()
    }
    
    override func tearDown() {
        SafeWKNavigation.toggleSafeDealloc()
        super.tearDown()
    }
    
    func testDidCommit() {
        let expectedNavigation = SafeWKNavigation()
        let webView = WKWebView(frame: .zero)
        var navigation: WKNavigation?
        

Review comment (bug):
```suggestion
        guard let current_original = class_getInstanceMethod(SafeWKNavigation.self, NSSelectorFromString("dealloc")),
              let current_swizzled = class_getInstanceMethod(SafeWKNavigation.self, #selector(nonCrashingDealloc)) else { return }
        method_exchangeImplementations(current_original, current_swizzled)
```

Code after:
//
//  WKWebView+RxTests.swift
//  Tests
//
//  Created by Giuseppe Lanza on 14/02/2020.
//  Copyright © 2020 Krunoslav Zaher. All rights reserved.
//

#if os(iOS) || os(macOS)

import WebKit
import RxCocoa
import RxSwift
import RxBlocking
import XCTest

@available(iOS 10.0, OSXApplicationExtension 10.10, *)
final class WKWebViewTests: RxTest {
    
    override func setUp() {
        super.setUp()
        SafeWKNavigation.toggleSafeDealloc()
    }
    
    override func tearDown() {
        SafeWKNavigation.toggleSafeDealloc()
        super.tearDown()
    }
    
    func testDidCommit() {
        let expectedNavigation = SafeWKNavigation()
        let webView = WKWebView(frame: .zero)
        var navigation: WKNavigation?
        
        let subscription = webView.rx.didCommit.subscribe(onNext: { nav in
            navigation = nav
        })

        webView.navigationDelegate!.webView?(webView, didCommit: expectedNavigation)

        XCTAssertEqual(expectedNavigation, navigation)
        subscription.dispose()
    }
    
    func testDidStartLoad() {
        let expectedNavigation = SafeWKNavigation()
        let webView = WKWebView(frame: .zero)
        var navigation: WKNavigation?
Repository: ReactiveX/RxSwift
File: RxCocoa/Foundation/URLSession+Rx.swift (Swift)

Code before:
    
    Any error during fetching of the response will cause observed sequence to terminate with error.
    
    If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
    will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
    
    If there is an error during JSON deserialization observable sequence will fail with that error.
    
    - parameter url: URL of `NSURLRequest` request.
    - returns: Observable sequence of response JSON.
    */
    public func json(url: Foundation.URL) -> Observable<Any> {
        self.json(request: URLRequest(url: url))
    }
}

extension Reactive where Base == URLSession {
/// Log URL requests to standard output in curl format.
   public static var shouldLogRequest: (URLRequest) -> Bool = { _ in
	   #if DEBUG
		   return true
	   #else
		   return false
	   #endif
   }
}


Review comment (bug):
Indentation seems wrong here
```suggestion
    /// A closure to determine if cURL-formatted request information shroud be loged
    /// for a specific `URLRequest`
    public static var shouldLogRequest: (URLRequest) -> Bool = { _ in
        #if DEBUG
            return true
        #else
            return false
        #endif
    }
}
```

Code after:
    
    Any error during fetching of the response will cause observed sequence to terminate with error.
    
    If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
    will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
    
    If there is an error during JSON deserialization observable sequence will fail with that error.
    
    - parameter url: URL of `NSURLRequest` request.
    - returns: Observable sequence of response JSON.
    */
    public func json(url: Foundation.URL) -> Observable<Any> {
        self.json(request: URLRequest(url: url))
    }
}

extension Reactive where Base == URLSession {
    /// Log URL requests to standard output in curl format.
    public static var shouldLogRequest: (URLRequest) -> Bool = { _ in
        #if DEBUG
            return true
        #else
            return false
        #endif
    }
}
Repository: ReactiveX/RxSwift
File: RxCocoa/Traits/Driver/Infallible+Driver.swift (Swift)

Code before:
//
//  Infallible+Driver.swift
//  RxCocoa
//
//  Created by Anton Siliuk on 14/02/2022.
//  Copyright © 2022 Krunoslav Zaher. All rights reserved.
//

import RxSwift

extension InfallibleType {
    /// Converts `InfallibleType` to `Driver`.
    ///
    /// - returns: Observable sequence.
    public func asDriver() -> Driver<Element> {
        let source = self.asObservable()
            .observe(on:DriverSharingStrategy.scheduler)
        return SharedSequence(source)
    }
}


Review comment (suggestion):
I'd go for a single-liner here
```suggestion
    public func asDriver() -> Driver<Element> {
        SharedSequence(asObservable().observe(on: DriverSharingStrategy.scheduler))
    }
```



Code after:
//
//  Infallible+Driver.swift
//  RxCocoa
//
//  Created by Anton Siliuk on 14/02/2022.
//  Copyright © 2022 Krunoslav Zaher. All rights reserved.
//

import RxSwift

extension InfallibleType {
    /// Converts `InfallibleType` to `Driver`.
    ///
    /// - returns: Observable sequence.
    public func asDriver() -> Driver<Element> {
        SharedSequence(asObservable().observe(on: DriverSharingStrategy.scheduler))
    }
}
Repository: ReactiveX/RxSwift
File: RxCocoa/Traits/Driver/Infallible+Driver.swift (Swift)

Code before:
//
//  Infallible+Driver.swift
//  RxCocoa
//
//  Created by Anton Siliuk on 14/02/2022.
//  Copyright © 2022 Krunoslav Zaher. All rights reserved.
//

import RxSwift

extension InfallibleType {
    /// Converts `InfallibleType` to `Driver`.
    ///
    /// - returns: Observable sequence.
    public func asDriver() -> Driver<Element> {
        SharedSequence(asObservable().observe(on:DriverSharingStrategy.scheduler))
    }
}


Review comment (suggestion):
```suggestion
        SharedSequence(asObservable().observe(on: DriverSharingStrategy.scheduler))
```

Code after:
//
//  Infallible+Driver.swift
//  RxCocoa
//
//  Created by Anton Siliuk on 14/02/2022.
//  Copyright © 2022 Krunoslav Zaher. All rights reserved.
//

import RxSwift

extension InfallibleType {
    /// Converts `InfallibleType` to `Driver`.
    ///
    /// - returns: Observable sequence.
    public func asDriver() -> Driver<Element> {
        SharedSequence(asObservable().observe(on: DriverSharingStrategy.scheduler))
    }
}
Repository: ReactiveX/RxSwift
File: Tests/RxSwiftTests/PrimitiveSequence+ConcurrencyTests.swift (Swift)

Code before:
// MARK: - Single
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension PrimitiveSequenceConcurrencyTests {
    func testSingleEmitsElement() async throws {
        let single = Single.just("Hello")

        do {
            let value = try await single.value
            XCTAssertEqual(value, "Hello")
        } catch {
            XCTFail("Should not throw an error")
        }
    }

    func testSingleThrowsError() async throws {
        let single = Single<String>.error(RxError.unknown)

        do {
            _ = try await single.value
            XCTFail("Should not proceed beyond try")
        } catch {
            XCTAssertTrue(true)
        }
    }

    func testSingleThrowsCancellationErrorWhenParentTaskIsCancelledButNoEventIsProduced() async throws {
        let single = Single<Void>.never()

        Task {
            do {
                try await single.value
                XCTFail("Should not proceed beyond try")
            } catch {
                XCTAssertTrue(Task.isCancelled)
                XCTAssertTrue(error is CancellationError)
            }
        }.cancel()
    }

    func testSingleDoesntThrowCancellationErrorWhenParentTaskIsCancelled() async throws {
        let single = Single.just(())

        let task = Task {
            do {
                try await single.value
                XCTAssertTrue(true)
            } catch {
                XCTFail()
            }
        }


Review comment (suggestion):
Lets shorten to something like this across the board

```suggestion
    func testSingleThrowsCancelleationWithoutEvents() async throws {
```

Code after:
// MARK: - Single
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension PrimitiveSequenceConcurrencyTests {
    func testSingleEmitsElement() async throws {
        let single = Single.just("Hello")

        do {
            let value = try await single.value
            XCTAssertEqual(value, "Hello")
        } catch {
            XCTFail("Should not throw an error")
        }
    }

    func testSingleThrowsError() async throws {
        let single = Single<String>.error(RxError.unknown)

        do {
            _ = try await single.value
            XCTFail("Should not proceed beyond try")
        } catch {
            XCTAssertTrue(true)
        }
    }

    func testSingleThrowsCancellationWithoutEvents() async throws {
        let single = Single<Void>.never()

        Task {
            do {
                try await single.value
                XCTFail("Should not proceed beyond try")
            } catch {
                XCTAssertTrue(Task.isCancelled)
                XCTAssertTrue(error is CancellationError)
            }
        }.cancel()
    }

    func testSingleNotThrowingCancellation() async throws {
        let single = Single.just(())

        let task = Task {
            do {
                try await single.value
                XCTAssertTrue(true)
            } catch {
                XCTFail()
            }
        }