简体   繁体   中英

Concat operator RxSwift

I have some code like this:

let first = Observable<Int>.create({ observer -> Disposable in
    observer.onNext(1)
    return Disposables.create()
})
let second = Observable.of(4, 5, 6)
let observableConcat = Observable.concat([first, second])
observableConcat.subscribe({ (event) in
    print(event)
})

What I know about the concat operator is "It subscribes to the first sequence of the collection, relays its elements until it completes, then moves to the next one. The process repeats until all the observables in the collection have been used". So that I expected the result from the code snippet would be 1, 4, 5, 6 but what I got is 1 only. Please teach me what I did misunderstand about the concat operator.

Thanks so much.

The first observable never ends. You can stop it adding take(1) :

Observable.concat([first.take(1), second])

In addition to CZ54's answer, you could do it like this

let first = Observable<Int>.create({ observer -> Disposable in
    observer.onNext(1)
    observer.onCompleted()
    return Disposables.create()
})

let second = Observable.of(4, 5, 6)
let observableConcat = Observable.concat([first, second])
observableConcat.subscribe({ (event) in
    print(event)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM