Search code examples
swiftreactive-programmingrx-swift

Is there a difference between Single.just(...) and Observable.just(...) in RxSwift?


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.


Solution

  • 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.