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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…