[英]Getting string from ViewModel to View in RxSwift
I am trying to get a string from ViewModel
to View
using PublishSubject()
but View
is not able to get it. 我正在尝试使用
PublishSubject()
从ViewModel
到View
的字符串,但是View
无法获取它。 Following is my code in ViewModel
: 以下是我在
ViewModel
代码:
var myImageURL: PublishSubject<String> = PublishSubject<String>()
self.myService.getImage(materialNo: materialNumber).subscribe(
onNext: { [weak self] imageURL in //I am able to get url here and want to send it to View, following doesn't work
self?.myImageURL.onNext(imageURL)
self?.myImageURL.onCompleted()
},
onError: { error in },
onCompleted: { }
)
.disposed(by: disposeBag)
Code in View
: View
代码:
let disposeBag = DisposeBag()
self.viewModel.myImageURL.subscribe(
onNext: {
print($0 + " image url")
self.myImageView.af_setImage(withURL: URL(string: $0)!, placeholderImage:UIImage(named: "tool_placeholder"))
},
onError: {
print(String(describing: $0).capitalized)
}
)
.disposed(by: disposeBag)
Although viewModel code works fine but I am not able to receive its value in View
. 虽然viewModel代码可以正常工作,但是我无法在
View
接收其值。
Edit1: Updated code in view with drive: Edit1:在驱动器视图中更新了代码:
self.viewModel.myImageURL
.asObservable()
.asDriver(onErrorJustReturn: "Error")
.drive(onNext: {
self. myImageView.af_setImage(withURL: URL(string: $0)!, placeholderImage:UIImage(named: "tool_placeholder"))
}
)
.disposed(by: disposeBag)
Looks like you subscribing the incorrect value? 看起来您订阅的值不正确? You defined:
您定义了:
var toolImageURL: PublishSubject<String> = PublishSubject<String>()
in your viewModel, but called subscribe
on viewModel.myImageURL
. 在您的viewModel中,但是在
viewModel.myImageURL
上称为subscribe
。
the publish subject you're using should be 'bound' to the ImageView using a 'driver' to ensure its code it's running on the main thread (it could crash otherwise). 您使用的发布主题应使用“驱动程序”“绑定”到ImageView,以确保其代码在主线程上运行(否则可能会崩溃)。
self.viewModel.myImageURL
.asObservable()
.asDriver(onErrorJustReturn: "Error")
.drive(self.myImageView.af_setImage(withURL: URL(string: $0)!,
placeholderImage:UIImage(named: "tool_placeholder")))
.addDisposableTo(self.disposeBag)
Try that firstly. 首先尝试一下。 Secondly, your code in the VM doesn't look that straight to me, why are you calling
onCompleted
in the onNext
block? 其次,您在VM中的代码对我而言并不那么直接,为什么要在
onNext
块中调用onCompleted
? Why not just using the onCompleted
block you left empty ad the bottom? 为什么不只使用
onCompleted
块在底部留空广告呢?
self.myService.getImage(materialNo: materialNumber).subscribe(
onNext: { [weak self] imageURL in //I am able to get url here and want to send it to View, following doesn't work
self?.myImageURL.onNext(imageURL)
self?.myImageURL.onCompleted()
},
onError: { error in },
onCompleted: { }
)
.disposed(by: disposeBag)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.