我的服务中有2个单独的数据集合。
Featured
和Standard
内容。
我有2个api调用来返回这些项目。它们可以单独使用,但是当我要获取两组数据,根据条件提供一些丰富的数据然后将它们返回给消费者时,我也有用例。
我希望我可以做这样的事情:
class ContentService: ContentServiceType {
let featured = PublishSubject<[Content]>()
let standard = PublishSubject<[Content]>()
let content: Observable<(featured: [Content], standard: [Content])>
private let client: Client<ContentAPI>
private let disposeBag = DisposeBag()
init(client: Client<ContentAPI>) {
self.client = client
content = Observable
.combineLatest(featured, standard)
.map { (featured, standard) -> (featured: [Content], standard: [Content]) in
/*
Do some enrichment and create then return new, updated versions
*/
return (featured: updatedFeatured, standard: updatedStandard)
}.share()
}
func fetchStandardContent(page: Int = 0, size: Int = 100) -> Single<Void> {
let params = ["page": page, "size": size]
let request: Single<Content> = client.request(.getStandardContent(params))
return request.map { [unowned self] launchers in
self.standard.onNext(content.props)
return ()
}
}
func fetchFeaturedContent(page: Int = 0, size: Int = 100) -> Single<Void> {
let params = ["page": page, "size": size]
let request: Single<Content> = client.request(.getFeaturedContent(params))
return request.map { [unowned self] content in
self.featured.onNext(content.props)
return ()
}
}
}
然后在我的应用程序的其他地方,我希望可以做类似的事情
contentSvc.content
.observeOn(MainScheduler.instance)
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.subscribe(onNext: { content in
/* do something w/ content */
}).disposed(by: disposeBag)
然后,每当调用contentSvc.fetchFeaturedContent
或contentSvc.fetchStandardContent
时,上方的contentSvc.content
订户都会获取新数据。
相反,content
似乎没有发出任何值。
答案 0 :(得分:2)
combineLatest
要求两个源都先发射。
我也许会考虑使用BehaviorSubject
或BehaviorRelay
而不是PublishSubject。
答案 1 :(得分:0)
我使用BehaviorRelay而不是PublishSubject,因为当从多个流绑定到PublishSubject(在应用之间共享)时,如果其中任何一个流发送完整消息,则PublishSubject可能会终止。中继类永远不会产生错误或永远不会完成。
let featured = BehaviorRelay(value: [Content]())
let standard = BehaviorRelay(value: [Content]())
func getContent() -> Observable<(featured: [Content], standard: [Content])> {
return Observable
.combineLatest(
featured.asObservable(),
standard.asObservable(),
resultSelector: { (featured, standard) -> (featured: [Content], standard: [Content]) in
return (featured: featured, standard: standard)
}
)
}
func addElemToFeatured() {
featured.accept([Content(name: "abc")])
}
func addElemToStandard() {
standard.accept([Content(name: "xyz")])
}
从初始化方法的不同类中调用getContent()方法。还可以从按钮操作等不同位置调用addElemToFeatured,addElemToStandard。
listener!.getContent()
.subscribe(onNext: { (featured, standard) in
print(featured)
print(standard)
}).disposed(by: disposeBag)