This might be a silly question, but I am relatively unfamiliar with using RxSwift - so I wanted to do a sanity check.
Is there any pragmatic difference between these two method definitions? Or are they basically identical?
func foo() -> Single<Bool> {
return Single<Bool>.create { single in
single(.success(true))
return Disposables.create()
}
}
func bar() -> Observable<Bool> {
return Observable.just(true)
}
Any differences between thread execution order or memory management that I should be aware of?
I'm just looking for any "gotchas" that I might not have otherwise known about.
CodePudding user response:
The Single.just(_:)
operator calls Observable.just(_:)
internally.
The Single type is a PrimitiveSequence type which is a wrapper around a standard Observable. This wrapper provides operators that ensure that a completed event is pushed immediately after a next event and it doesn't allow you to subscribe to onCompleted events. Specifically, when it comes to just(_:)
there is little difference. The Single type adds a function to the call stack and a bit of extra memory which is used to ensure exactly one next event is emitted. That assurance does nothing in the context of a just
though which will only ever emit a single element anyway.
As @LouFranco mentions in his answer and I say above, the contract of Single is different, but the type does not provide any compile time guarantees. You can still call asSingle()
on a normal Observable, push out a completed event without a next event, or push out two next events, and the code will compile just fine but produce a runtime error. Since the type doesn't provide a guarantee against a runtime error, IMO it doesn't provide enough value to warrant its use. YMMV.
CodePudding user response:
The difference is the promise you are making to the caller. If you return a Single
, you are saying that you are getting exactly one value. I don’t need to look at the implementation to see that and I am guaranteed that this will always be the case.
In the Observable
case, I am not guaranteed that more values aren’t coming. Even if I look at the implementation and see it’s just a just
, that doesn’t mean the code won’t change.