我想链接以下操作
getStuff
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)
}
}
}
答案 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)
您还可以通过getStuff
或Observable
返回Single
被动,并通过flatMap
将其包含在链中。