Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
889 views
in Technique[技术] by (71.8m points)

rx 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)
}
question from:https://stackoverflow.com/questions/65864891/observable-only-emits-one-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...