Given a service class like this:
class Service {
let networkService = NetworkService()
func handleJobA(input: String) -> Observable
You need a serial Scheduler that is dedicated to that service. Here is an example that can be pasted to a playground:
/// playground
import RxSwift
class Service {
func handleJobA(input: String) -> Observable<String> {
return Observable.create { observer in
print("start job a")
sleep(3)
observer.onNext(input)
print("complete job a")
observer.onCompleted()
return Disposables.create()
}.subscribeOn(scheduler)
}
func handleJobB(input: String) -> Observable<String> {
return Observable.create { observer in
print("start job b")
sleep(3)
observer.onNext(input)
print("complete job b")
observer.onCompleted()
return Disposables.create()
return Disposables.create()
}.subscribeOn(scheduler)
}
let scheduler = SerialDispatchQueueScheduler(internalSerialQueueName: "Service")
}
let service = Service()
_ = Observable.from(["hello","world","swift"])
.flatMap { service.handleJobA(input: $0) }
.subscribe(onNext:{
print("result " + $0)
})
_ = Observable.from(["hello","world","swift"])
.flatMap { service.handleJobB(input: $0) }
.subscribe(onNext:{
print("result " + $0)
})
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
maybe you want concat
operator,i wrote some test codes below see if this you want :
func sleepAndPrint(label:String) -> Observable<String> {
return Observable.create { obser -> Disposable in
DispatchQueue.global().async {
sleep(3)
print("\(label) come")
obser.onNext(label)
obser.onCompleted()
}
return Disposables.create()
}
}
Observable.from(["hello","world","swift"])
// we need observable of observable sequences so just use map
// Observable<Observable<String>> in this case
.map{
sleepAndPrint(label: $0)
}
// Concatenates all inner observable sequences, as long as the previous observable sequence terminated successfully.
.concat()
.subscribe(onNext:{
print("subscribe: " + $0)
})
.addDisposableTo(disposeBag)
prints :
hello come
subscribe: hello
world come
subscribe: world
swift come
subscribe: swift