我想连锁经营
创建用户并验证
创建匿名用户(用户)
验证用户->验证用户
如果验证成功返回verifiedUser否则返回user
获取coredatagetStuff
如果stuff.count>0,则上载具有用户凭据的内容uploadStuff
最后报告所有操作的结果
我写了createUserandVerify如下。我想知道我应该如何用被动的方式写uploadStuff。上载功能取决于用户凭据。因此,它只能在createUserandVerify之后运行。我知道我可以检查uploadStuff内的数组计数并返回空的,但我想知道最佳实践。

func createUserandVerify() -> Single<User> {
    return Service.sharedInstance.generateAnonUser()
        .flatMap{ user in
            if Service.sharedInstance.isOldRegisteredUser {
                print("It is old user")
                // We need to verify the receipt
                return  Service.sharedInstance.verifyReceipt()
                    .flatMap { verifiedUser in
                        print("Returning Verified new user [Verification Success]")
                        return Single.just((verifiedUser))

                    }.catchError{ error ->Single<User> in
                        print("Returning firstly created user [Verification Failed]")
                        print("Error Type: \(error)")
                        return Single.just(user)

                }
            } else {
                //Normal anonymous old user
                print("Returning firstly created user [Anonymous]")
                return Single.just(user)
            }
    }
}

最佳答案

假设(因为我没有与Single合作,所以我将它们改为Observable):

func createUserandVerify() -> Observable<User>
func getStuff() -> [Stuff]
func uploadStuff(_ user: User) -> Observable<String>

createUserandVerify()应该使用onError发布错误,因此如果出现错误,将不会调用uploadStuff
可能的解决方案:
enum CustomError: Error {
    case instanceMissing
    case notEnoughStuff
}

createUserandVerify()
    .flatMap { [weak self] (user) -> Observable<String> in
        guard let strongSelf = self else { throw CustomError.instanceMissing }
        guard strongSelf.getStuff().count > 0 else { throw CustomError.notEnoughStuff }
        return strongSelf.uploadStuff(user)
    }
    .subscribe(
        onNext: { stringResult in
          // print result from 'uploadStuff'
          print(stringResult)
    },
        onError: { error in
          // will be reached if something goes
          // wrong in 'createUserandVerify' or 'uploadStuff'
          // or if one of your custom errors in 'flatMap' are thrown
          print(error)
    })
    .disposed(by: disposeBag)

您还可以通过返回getStuffObservable使Single反应,并通过flatMap将其包含在链中。

关于swift - 使用RxSwift进行链接操作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49831545/

10-10 20:55