【Xcode/Swift】Difference Between Hot Observable and Cold Observable of RxSwift : Explained Eminem-style

Yo, what’s up kiddo? I’m here to drop some knowledge bombs about RxSwift, Eminem style! So listen up!

You know how sometimes you’re waiting for your ice cream to arrive, and you’re just standing there, getting impatient? Well, that’s like a “Hot Observable” in RxSwift. It’s like the ice cream truck that’s already out on the road, serving ice cream to everyone who comes up to it. It doesn’t matter if you just got there or if you’ve been waiting for a while, you’ll get the same ice cream. Here’s an example in code:

import RxSwift

let hotObservable = Observable<Int>.interval(1, scheduler: MainScheduler.instance)

hotObservable.subscribe(onNext: { num in
    print("Ice cream number: \(num)")
}).disposed(by: DisposeBag())

In this code, hotObservable is like the ice cream truck that’s already driving around, and it’s giving out ice cream numbers every second. You can see that we’re just subscribing to it, and we’ll get the same ice cream numbers that it’s giving out to everyone else, no matter when we subscribe.

Now, let’s talk about “Cold Observable.” Imagine you have a stash of ice cream in your freezer at home, and you’re sharing it with your friends. You can give them each a scoop from the same stash, but they’ll each get their own scoops. That’s like a “Cold Observable” in RxSwift. Here’s an example in code:

import RxSwift

let coldObservable = Observable<Int>.create { observer in
    for num in 0..<5 {
        observer.onNext(num)
    }
    observer.onCompleted()
    return Disposables.create()
}

coldObservable.subscribe(onNext: { num in
    print("Scoop number: \(num)")
}).disposed(by: DisposeBag())

In this code, coldObservable is like the stash of ice cream in your freezer that you’re sharing with your friends. You can see that we’re just subscribing to it, and we’ll get our own scoops from the same stash, but each scoop will be our own.

So, in summary, a “Hot Observable” is like an ice cream truck that’s already driving around and serving the same ice cream to everyone, no matter when they come. And a “Cold Observable” is like a stash of ice cream in your freezer that you’re sharing with your friends, and they’ll each get their own scoops. Hope that clears things up for you, little buddy! Keep on coding!