从ViewModel获取字符串到RxSwift中的View

时间:2018-02-11 10:44:39

标签: ios swift mvvm rx-swift

我正在尝试使用ViewModelViewPublishSubject()获取字符串,但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中收到它的值。

EDIT1: 使用drive更新了代码:

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)

2 个答案:

答案 0 :(得分:0)

看起来您订阅了错误的值?你定义了:

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

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

答案 1 :(得分:0)

您正在使用的发布主题应该被绑定&#39;使用&#39;驱动程序&#39;到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)

首先尝试一下。 其次,您在VM中的代码并不直接看我,为什么要在onCompleted块中调用onNext?为什么不直接使用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)