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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With