使用RxSwift进行链接操作

时间:2018-04-14 12:38:00

标签: swift rx-swift

我想链接以下操作

  • createUserandVerify
    • 创建匿名用户(用户)
    • 验证用户 - > verifiedUser
    • 如果验证成功,则返回VerifiedUser else return user
  • 获取coredata的内容getStuff
    • 如果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)
            }
    }
}

1 个答案:

答案 0 :(得分:0)

假设(因为我没有使用过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将其包含在链中。