Search code examples
rx-swift

Observable.from subscribe closure called twice


When executed the code below will print "subscribe" twice. Why? RxSwift 5.0

import UIKit
import RxSwift

class ViewController: UIViewController {

    let data = Data(repeating: 100, count: 1_000_000_000_0)

    override func viewDidLoad() {
        super.viewDidLoad()


        let disposeBag = DisposeBag()
        Observable<Data>
            .from(data)
            .subscribe( { _ in print("subscribe") } )
            .disposed(by: disposeBag)

    }

}

Solution

  • This is a correct behaviour. You're creating an Observable that only contains a single value which causes two events to fire:

    1. Next Event (containing your data object)
    2. Complete Event that indicates that the stream has completed.

    I suspect that in what you're after is the first (Next) event. Change your code from:

    Observable<Data>
            .from(data)
            .subscribe( { _ in print("subscribe") } )
            .disposed(by: disposeBag)
    

    To:

    Observable<Data>
            .from(data)
            .subscribe(onNext: { _ in print("subscribe") } )
            .disposed(by: disposeBag)
    

    Which will give you just the Next event containing your Data object.