Reputation: 646
I'm new in RxSwift, I don't understand what is difference between do(onNext:)
and subscribe(onNext:)
.
I google it but did't found good resources to explain the difference.
Upvotes: 26
Views: 13616
Reputation: 256
The do operator allows you to insert side effects; that is, handlers to do things that will not change the emitted event in any way. do will just pass the event through to the next operator in the chain.
The method for using the do operator is here.
And you can provide handlers for any or all of these events.
Let's say We have an observable that never emits anything. Even though it emits nothing, it is still an observable and we can subscribe to it. do operator allows us to do something when a subscription was made to it. So below example will print "Subscribed" when a subscription was made to that observable.
Feel free to include any of the other handlers if you’d like; they work just like subscribe’s handlers do
let observable = Observable<Any>.never()
let disposeBag = DisposeBag()
observable
.do(onSubscribe: {
print("Subscribed")
})
.subscribe(
onNext: { element in
print(element)
},
onCompleted: {
print("Completed")
},
onDisposed: {
print("Disposed")
}
)
.disposed(by: disposeBag)
Upvotes: 12
Reputation: 33967
At the beginning of a cold Observable chain there is a function that generates events, for e.g. the function that initiates a network request.
That generator function will not be called unless the Observable is subscribed to (and by default, it will be called each time the observable is subscribed to.) So if you add a do(onNext:)
to your observable chain, the function will not be called and the action that generates events will not be initiated. You have to add a subscribe(onNext:)
for that to happen.
(The actual internals are a bit more complex than the above description, but close enough for this explanation.)
Upvotes: 28