Limiting concurrent access to a service class with RxSwift

后端 未结 2 1440
春和景丽
春和景丽 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:42

    maybe you want concat operator,i wrote some test codes below see if this you want :

     func sleepAndPrint(label:String) -> Observable {
    
    
            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> 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
    

提交回复
热议问题