我是第一次使用RxSwift。它将从我的服务器加载帖子列表。第一次只需要运行loadPostList,但只需初始化模型,就会调用nextPage。
请让我知道我做错了什么。
class PostNetworkModel {
var nextPage:BehaviorSubject<Void> = BehaviorSubject(value: ())
var reFresh:BehaviorSubject<Void> = BehaviorSubject(value: ())
var raiseError:BehaviorSubject<Void> = BehaviorSubject(value: ())
var isLoadingComplete = false
private var pageNo = BehaviorRelay(value: 1)
var postList : BehaviorRelay<[Post]> = BehaviorRelay(value: [])
let disposeBag = DisposeBag()
init() {
loadPostList()
.bind(to: postList)
.disposed(by: disposeBag)
postList
.asObservable()
.subscribe({ ( _) in
self.isLoadingComplete = true
})
.disposed(by: disposeBag)
nextPage
.asObservable()
.subscribe(onNext: { [weak self] ( _) in
print("nextPage")
if (self?.isLoadingComplete)!{
self?.isLoadingComplete = false
self?.pageNo.accept(self!.pageNo.value + 1)
}
})
.disposed(by: disposeBag)
}
}
BehaviorSubject
接受初始值作为构造函数参数,因为其规范如下:
观察者可以订阅主题以接收最后(或初始)值以及所有后续通知。
意思是nextPage
将触发下一个甚至订阅。您可能希望将此类的所有BehaviorSuject
更改为PublishSubject
class PostNetworkModel {
var nextPage:PublishSubject<Void> = PublishSubject()
var reFresh:PublishSubject<Void> = PublishSubject()
var raiseError:PublishSubject<Void> = PublishSubject()
var isLoadingComplete = false
private var pageNo = BehaviorRelay(value: 1)
var postList : PublishRelay<[Post]> = PublishRelay()
let disposeBag = DisposeBag()
init() {
loadPostList()
.bind(to: postList)
.disposed(by: disposeBag)
postList
.asObservable()
.subscribe({ ( _) in
self.isLoadingComplete = true
})
.disposed(by: disposeBag)
nextPage
.asObservable()
.subscribe(onNext: { [weak self] ( _) in
print("nextPage")
if (self?.isLoadingComplete)!{
self?.isLoadingComplete = false
self?.pageNo.accept(self!.pageNo.value + 1)
}
})
.disposed(by: disposeBag)
}
}
请注意,我保持pageNo
为BehaviorRelay
,因为这个observable有一个初始值是有道理的。