Limiting concurrent access to a service class with RxSwift

后端 未结 2 1434
春和景丽
春和景丽 2021-01-20 20:20

Given a service class like this:

class Service {
    let networkService = NetworkService()

    func handleJobA(input: String) -> Observable

        
2条回答
  •  有刺的猬
    2021-01-20 20:25

    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 {
    
            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 {
            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
    

提交回复
热议问题