以下代码有效:
td item
在上面的代码中调用onCompleted方法但不在下面的代码中。
我正在尝试使用UITableView中的刷新触发器来刷新内容。我想在开始时加载内容,所以我在ViewModel的以下代码中使用 let provider = RxMoyaProvider<MyAPI>( stubClosure: MoyaProvider.delayedStub(3))
provider
.request(.studentSearch(query: ""))
.retry(3)
.observeOn(MainScheduler.instance)
.asObservable()
.mapJSON()
.map { respJSON in
guard let studentsJsonArray = JSON(respJSON)["students"].array else {
throw APIError.wrongJSONParsing
}
return studentsJsonArray.map {
guard let students = Student.fromJSON($0) else {
fatalError("Invalid Student Object")
}
return students
} as [Student]
}
.subscribe(onNext: {
print($0)
}, onCompleted: {
print($0) // This one is being called.
})
.disposed(by: rx.disposeBag)
startWith(())
在控制器中我在viewdidload中调用以下内容。
let results: Driver<[Student]>
var refreshTrigger = PublishSubject<Void>()
results = refreshTrigger
.startWith(())
.do(onNext: {
execute.value = true
})
.flatMapLatest {
provider
.request(.studentSearch(query: ""))
.retry(3)
.observeOn(MainScheduler.instance)
.asObservable()
}
.mapJSON()
.map { respJSON in
guard let studentsJsonArray = JSON(respJSON)["students"].array else {
throw APIError.wrongJSONParsing
}
return studentsJsonArray.map {
guard let students = Student.fromJSON($0) else {
fatalError("Invalid Student Object")
}
return students
}
}
.do(onNext: {
items.value = $0
execute.value = false
noResults.value = items.value.isEmpty
}, onCompleted: {
print($0)
})
.asDriver(onErrorJustReturn: [])
此处onCompleted未被调用。我不知道原因是什么?请帮帮我。
答案 0 :(得分:0)
flatMapLatest不会发送onCompleted事件,除非它的输入(在你的情况下是PublishSubject)完成。 Moya请求发送它们自己的onCompleted事件,但是当flatMapLatest合并结果时,这些事件会被过滤掉。 换句话说,从PublishSubject到数据源的长期订阅没有完成,也不应该。 (编辑)的 (否则在第一次加载后你将失去刷新功能。)
我从RxSwift Slack频道获得Zsolt Varadi的帮助。
这是解决方案
results = refreshTrigger
.startWith(())
.do(onNext: {
execute.value = true
})
.flatMapLatest {
provider
.request(.studentSearch(query: ""))
.retry(3)
.observeOn(MainScheduler.instance)
.asObservable()
.mapJSON()
.map { respJSON in
guard let studentsJsonArray = JSON(respJSON)["students"].array else {
throw APIError.wrongJSONParsing
}
return studentsJsonArray.map {
guard let students = Student.fromJSON($0) else {
fatalError("Invalid Student Object")
}
return students
} as [Student]
}
.map { StudentGroup(header: "Follower", items: $0) }
.toArray()
.catchErrorJustReturn([])
.do(onNext: {
studentGroups.value = $0
execute.value = false
guard let isEmpty = studentGroups.value.first?.items.isEmpty else {
return
}
noResults.value = isEmpty
})
}
.asDriver(onErrorJustReturn: [])