gpt4 book ai didi

ios - 在 RxSwift 中从 ViewModel 获取字符串到 View

转载 作者:行者123 更新时间:2023-11-30 11:46:56 24 4
gpt4 key购买 nike

我尝试使用 PublishSubject()ViewModelView 获取字符串,但 View 不是能够得到它。以下是我在 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)

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)

虽然 viewModel 代码工作正常,但我无法在 View 中接收其值。

编辑1:使用驱动器更新了 View 中的代码:

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)

最佳答案

看来您订阅的值不正确?您定义:

var toolImageURL: PublishSubject<String> = PublishSubject<String>()

在您的 viewModel 中,但在 viewModel.myImageURL 上调用 subscribe

关于ios - 在 RxSwift 中从 ViewModel 获取字符串到 View,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48730658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com