[英]Return Observer.create Not returning and code next to it not working using RxSwift
Well i am pretty much new to reactive programming.好吧,我对反应式编程非常陌生。 problem is, I have a function(A) which returns an object, now I have another function(B) which subscribes returning object from function A and I make function B also as returning an other object in that subscribe, now this whole return this is not work. problem is, I have a function(A) which returns an object, now I have another function(B) which subscribes returning object from function A and I make function B also as returning an other object in that subscribe, now this whole return this是不行的。 I have no idea why is happening.我不知道为什么会这样。 Any help would be appreciated.任何帮助,将不胜感激。 Thanks Function A谢谢Function A
func getClassById(classId: Int) -> Observable<Bool> {
return Observable.create{[weak self] observer -> Disposable in Alamofire.request("URL", method:.get, parameters: nil, encoding: JSONEncoding.default, headers: self!.getRequestHeader())
.validate()
.responseJSON{ response in
switch response.result {
do {
let assingnedClass = try JSONDecoder().decode(AssignedClassModel.self, from: data)
observer.onNext(true)
} catch {
observer.onError(error)
}
case .failure(let error):
observer.onError(error)
}
}
return Disposables.create()
}
}
Function B Function B
func getAssignedClassData(classId: Int) -> Observable<[StudentModel]> {
return Observable.create{[weak self] observer -> Disposable in // from here code is not going further.
APIService.singelton
.getClassById(classId: classId)
.asObservable()
.subscribe(onNext: { [weak self] assingnedClass in
let studentsData = Array(Database.singleton.fetchStudents(byCLassId: classId))
print(studentsData)
observer.onNext(studentsData)
}, onError: { error in
print(error)
}).disposed(by: self!.disposeBag)
return Disposables.create()
}
}
Function B2 Function B2
func getAssignedClassData(classId: Int) -> Observable<[StudentModel]> {
return APIService.singelton
.getClassById(classId: classId)
.do(onError: { error in
print(error)
})
.map({ [weak self] assingnedClass in
return Array(Database.singleton.fetchStudents(byCLassId: classId))
// this code will not be triggered as it is after return.
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "tabBarVC") as? TabBarViewController
let transition = CATransition()
transition.duration = 0.5
transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.default)
transition.type = CATransitionType.fade
self?.navigationController?.view.layer.add(transition, forKey: nil)
self?.navigationController?.pushViewController(vc!, animated: true)
})
}
There is no Observable creation needed in Function B. If you want to transform one observable to another you can use map
operator . Function B 中不需要创建 Observable。如果要将一个 observable 转换为另一个,可以使用map
operator 。
There is an error handling trouble in Function B. Error will be caught, but Observable will never be completed. Function B 中存在错误处理问题。错误会被捕获,但 Observable 永远不会完成。 In my example I used just side effect for printing error, so error will be propagated and map
will not run.在我的示例中,我只使用了打印错误的副作用,因此错误将被传播并且map
将不会运行。 There are some strategies forerror handling in RxSwift . RxSwift 中有一些错误处理策略。
Function B doesn't need asObservable
. Function B 不需要asObservable
。
The result of Function A ( assingnedClass
) is not used.不使用 Function A ( assingnedClass
) 的结果。 Probably the real code was simplified.可能真正的代码被简化了。
There is no observer.onCompleted()
after observer.onNext()
in Function A. Your observable will not be completed and disposed at time. Function A 中的observer.onCompleted()
observer.onNext()
你的observable 不会及时完成和处置。
Here is my example:这是我的例子:
class StudentService {
...
func getAssignedClassData(classId: Int) -> Observable<[StudentModel]> {
return APIService.singelton
.getClassById(classId: classId)
.do(onError: { error in
print(error)
})
.map { _ in Array(Database.singelton.fetchStudents(byCLassId: classId)) }
}
}
class SomeController: UIViewController {
...
func fetchStudentsAndPushViewController() {
studentService
.getAssignedClassData(classId: classId)
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] _ in
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "tabBarVC") as? TabBarViewController
let transition = CATransition()
transition.duration = 0.5
transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.default)
transition.type = CATransitionType.fade
self?.navigationController?.view.layer.add(transition, forKey: nil)
self?.navigationController?.pushViewController(vc!, animated: true)
})
.disposed(by: self!.disposeBag)
}
}
BTW.顺便提一句。 You can try RxAlamofire for you APIService
so you won't need to wrap the request into Observable by yourself.您可以为您的APIService
尝试RxAlamofire ,这样您就不需要自己将请求包装到 Observable 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.