RxSwift:如何让一个observable触发另一个?

时间:2017-04-18 08:31:26

标签: rx-swift

假设我有可观察的class PaginationNetworkModel<T1: Mappable>: NSObject { let refreshTrigger = PublishSubject<Void>() let loadNextPageTrigger = PublishSubject<Void>() let loading = Variable<Bool>(false) let elements = Variable<[T1]>([]) var offset:Int = 0 let error = PublishSubject<Swift.Error>() private let disposeBag = DisposeBag() override init() { super.init() let refreshRequest = loading.asObservable() .sample(refreshTrigger) .flatMap { loading -> Observable<Int> in if loading { return Observable.empty() } else { return Observable<Int>.create { observer in observer.onNext(0) observer.onCompleted() return Disposables.create() } } } let nextPageRequest = loading.asObservable() .sample(loadNextPageTrigger) .flatMap { [unowned self] loading -> Observable<Int> in if loading { return Observable.empty() } else { return Observable<Int>.create { [unowned self] observer in self.offset += 1 observer.onNext(self.offset) observer.onCompleted() return Disposables.create() } } } let request = Observable .of(refreshRequest, nextPageRequest) .merge() .shareReplay(1) let response = request.flatMap { offset -> Observable<[T1]> in self.loadData(offset: offset) .do(onError: { [weak self] error in self?.error.onNext(error) }).catchError({ error -> Observable<[T1]> in Observable.empty() }) }.shareReplay(1) Observable .combineLatest(request, response, elements.asObservable()) { [unowned self] request, response, elements in return self.offset == 0 ? response : elements + response } .sample(response) .bind(to: elements) .addDisposableTo(rx_disposeBag) Observable .of(request.map{_ in true}, response.map { $0.count == 0 }, error.map { _ in false }) .merge() .bind(to: loading) .addDisposableTo(rx_disposeBag) } func loadData(offset: Int) -> Observable<[T1]> { return Observable.empty() } ,我正在尝试创建可观察的A,它会发出两个事件:B发出事件时的第一个事件,以及5秒后的第二个事件。< / p>

到目前为止,我有以下内容:

A

这很有效,但我觉得从一个闭包中订阅self.B = Observable.create { [unowned self] observer in self.A.subscribe(onNext: { observer.onNext(0) self.delay(5) { observer.onNext(1) } }) return Disposables.create() } 是不可饶恕的。有没有更好的方法呢?

谢谢!

1 个答案:

答案 0 :(得分:1)

解决方案是为延迟的observable重用a observable。下面是代码,以及概念证明。

let a = button.rx.tap.asObservable()
let delay = a.delay(5.0, scheduler: MainScheduler.instance)
let b = Observable.of(a, delay).merge()

b.subscribe(onNext: {
    print("foo")
}).disposed(by: bag)