我需要调用一个函数序列来获取通知所需的所有信息。首先subscribe打开会话,然后queryNotification监听所有传入的通知,一旦收到通知,需要使用queryNotification返回的notificationId调用getNotificationAttrs,然后使用getNotificationAttrs返回的appIdentifier调用getAppAttributes,我需要queryNotification、getNotificationAttrs和getAppAttributes的组合结果。函数的外观如下所示:
func subscribeNotification() -> Single<Info>
func queryNotification() -> Observable<Notification>
func getNotificationAttrs(uid: UInt32, attributes: [Attribute]) -> Single<NotificationAttributes>
func getAppAttributes(appIdentifier: String, attributes: [AppAttribute]) -> Single<NotificationAppAttributes>棘手的部分是queryNotification返回Observable,而getNotificationAttrs和getAppAttributes都返回Single。我想把它们链接在一起是这样的:
subscribeNotification()
.subscribe(onSuccess: { info in
queryNotification()
.flatMap({ notification in
return getNotificationAttributes(uid: notification.uid, attributes: [.appIdentifier, .content])
})
.flatMap({ notifAttrs
return getAppAttributes(appIdentifier: notifAttrs.appIdentifier, attributes: [.displayName])
})
.subscribe {
// have all the result from last two calls
}
})这可行吗?任何方向都很受欢迎!谢谢!
发布于 2019-02-23 10:02:48
最明显也是最正确的解决方案是将你的Single提升为Observable。而且,我不是第一个subscribe的粉丝。你最终会得到一个缩进金字塔。
我遵循您的意见,需要来自所有queryNotification(),getNotificationAttrs(did:attributes:)和getAppAttributes(appIdentifier:attributes:)的值……
let query = subscribeNotification()
.asObservable()
.flatMap { _ in queryNotification() }
.share(replay: 1)
let attributes = query
.flatMap { getNotificationAttrs(uid: $0.uid, attributes: [.appIdentifier, .content]) }
.share(replay: 1)
let appAttributes = attributes
.flatMap { getAppAttributes(appIdentifier: $0.appIdentifier, attributes: [.displayName]) }
Observable.zip(query, attributes, appAttributes)
.subscribe(onNext: { (query, attributes, appAttributes) in
})上述步骤将遵循您概述的步骤,每次发出新通知时都会调用subscribe。
还要注意上面的代码读起来很像同步代码(只是有一些额外的包装)。
https://stackoverflow.com/questions/54834452
复制相似问题