我有和observable,如果函数返回它,它永远不会发送onNext,但如果我在返回它的函数中订阅它,则会调用onNext。
class InfoViewModel {
func refreshPushToken() {
PushNotificationService.sharedInstance.pushToken!
.flatMapLatest { (pushToken: String) -> Observable<Result<User>> in
return UserService.registerPushToken(pushToken)
}
.subscribe { (event ) in
print(event)
}
.addDisposableTo(disposeBag)
}
}
struct UserService {
....
static func registerPushToken(_ pushToken: String) -> Observable<Result<User>> {
...
return self.postUser(user: user)
}
static fileprivate func postUser(user: User) -> Observable<Result<User>> {
let rxProvider: RxMoyaProvider<Backend> = RxMoyaProvider<Backend>(endpointClosure: Backend.endpointClosure)
return rxProvider.request(Backend.register(user: user))
.mapObject(type: User.self)
.map({ (user: User) -> Result<User> in
LogService.log(level: .debug, action: "postUser", message: "Posted user with success", parameters: ["user": user.deviceId])
return .success(user)
})
.catchError({ error -> Observable<Result<User>> in
LogService.log(level: .error, action: "postUser", message: "Error posting user", parameters: ["user": user.deviceId, "error": error.localizedDescription])
return Observable.just(.failure(error))
})
}
}
但如果我这样做
rxProvider.request(Backend.register(user: user))
...
.subscribe { (event ) in
print(event)
}
在UserService中,我将收到下一个活动。
我曾尝试在InfoViewModel中的observable上使用debug()
,有订阅,我从未收到过任何事件。
答案 0 :(得分:0)
所以我想通了,我在方法中创建了RxMoyaProvider,所以当我退出方法的范围时,它就被解除了分配。这意味着在订阅它时,它无法再创建请求。这不会失败的原因是因为创建了observable
open func request(_ token: Target) -> Observable<Response> {
// Creates an observable that starts a request each time it's subscribed to.
return Observable.create { [weak self] observer in
let cancellableToken = self?.request(token) { result in
switch result {
case let .success(response):
observer.onNext(response)
observer.onCompleted()
case let .failure(error):
observer.onError(error)
}
}
return Disposables.create {
cancellableToken?.cancel()
}
}
}
如您所见,请求在订阅时调用,但由于self
已被释放,因此请求从未被触发。我所得到的只是一个空洞的观察者。