Search code examples
observablerx-swift

Observable only emits one value?


I'm new in RxSwift, I have this code snipped that print in my console:

next(second value)

completed

but I was expecting this result:

next(first value)

next(second value)

completed

why is not reacting twice the subscribe? I understand that in react, the observable emits and trigger the subscribe evert time that the variable that we are observing change but the code is not showing this. Do I misunderstand the concept?

var mutableString = "first value"
mutableString = "second value"

var stringObservable: Observable<String> = Observable.of(mutableString)
        
stringObservable.subscribe { event in
    print(event)
}

Solution

  • When the program runs, it goes through each line of code step by step. So first it creates the variable mutableString and assigns "first value" to it. Then in the next line it assigns "second value" to the variable.

    Then it creates the variable stringObservable of type Observable<String> and assigns Observable.of(mutableString) to it, since mutableString contains "second value", that is what the value inside the Observable is assigned.

    Note that the Observable has it's own variable inside it so changing the value of mutableString will not affect the Observable.

    To get the output you are looking for, you need to pass all of the values you want the Observable to output at the time of creation, like this:

    let stringObservable: Observable<String> = Observable.of("first value", "second value")
    stringObservable.subscribe { event in
        print(event)
    }
    

    Another option would be to create an Observable that has a function which outputs the values:

    func makeObservable(from array: [String]) -> Observable<String> {
        Observable<String>.create { observer in
            for each in array {
                observer.onNext(each)
            }
            observer.onCompleted()
            return Disposables.create()
        }
    }
    

    This is basically how Observable's of(_:) operator is implemented. Every time the resulting Observable is subscribed to, it will run the closure that was passed into the create function causing it to emit the two values (and the completed event) again.