Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between .subscribe and .drive

I am quite new in Reactive Programming, Here is what I'm trying

.drive

searchController.rx.text
        .asDriver()
        .drive(onNext: { (element) in
            print(element)
        }).disposed(by: disposeBag)

.subscribe

searchController.rx.text
        .asObservable()
        .subscribe(onNext: { (element) in
            print(element)
        }).disposed(by: disposeBag)

both blocks are working exactly the same, What is the purpose of using .drive over .subscribe? In which scenario we should use .drive over .subscribe ?

Any help will be appreciated

like image 856
Trool Destroyer Avatar asked Jan 05 '18 13:01

Trool Destroyer


1 Answers

Driver is a bit different from Observable. From documentation:

Trait that represents observable sequence with following properties:

  • it never fails
  • it delivers events on MainScheduler.instance
  • share(replay: 1, scope: .whileConnected) sharing strategy

I assume that searchController.rx.text never fails and share isn't required in this situation.

So we have only one point that makes them different in your situation:

  • it delivers events on MainScheduler.instance

And you can check it yourself. Before subscribe insert this and your events won't be delivered on main thread:

.observeOn(ConcurrentDispatchQueueScheduler(qos: .background))

That is how I checked it in my code:

something
    .asObservable()
    .observeOn(ConcurrentDispatchQueueScheduler(qos: .background))
    .subscribe(onNext: { _ in
        print("observable is on main thread: ", Thread.isMainThread)
    })

something
    .asDriver()
    .drive(onNext: { _ in
        print("driver is on main thread: ", Thread.isMainThread)
    }) 

Logs:

driver is on main thread: true

observable is on main thread: false

In which scenario we should use .drive:

When working with UI. Why? From documentation:

Important

Use UIKit classes only from your app’s main thread or main dispatch queue, unless otherwise indicated. This restriction particularly applies to classes derived from UIResponder or that involve manipulating your app’s user interface in any way.

like image 187
iWheelBuy Avatar answered Nov 18 '22 11:11

iWheelBuy