如何在按钮点击时观察 PublishSubject
Posted
技术标签:
【中文标题】如何在按钮点击时观察 PublishSubject【英文标题】:how to observe PublishSubject on button tap 【发布时间】:2017-05-16 14:14:09 【问题描述】:我正在处理这种情况,我想在这里应用 RxSwift。
我有.xib
UIView 和按钮。
class RightButtonItemView: UIView
@IBOutlet weak var rightButtonimageView: UIImageView!
@IBOutlet weak var rightButtonButton: UIButton!
let performEventSegue = PublishSubject<Bool>()
class func instanceFromNib() -> RightButtonItemView
return UINib(nibName: "NotificationView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! RightButtonItemView
override func awakeFromNib()
//I'm not sure how should I link button tap and my subject
rightButtonButton.rx.tap
我在我的 viewController 中创建了这个视图的一个实例
var rightButtonItemView = RightButtonItemView.instanceFromNib()
从我的 segue 中点击这个按钮我需要转到下一个 VC,所以我订阅了 UIView 的主题
rightButtonItemView.performEventSegue.asObserver().subscribe(onNext: (isAuthorized) in
if isAuthorized
let storyboard = UIStoryboard(name: "Notifications", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "UserNotificationsViewController")
self.present(viewController, animated: true, completion: nil)
)
但我不知道如何将按钮点击与更改我的发布主题的状态联系起来?
【问题讨论】:
【参考方案1】:您在这种情况下使用bind
运算符:
class RightButtonItemView: UIView
@IBOutlet weak var rightButtonimageView: UIImageView!
@IBOutlet weak var rightButtonButton: UIButton!
let performEventSegue = PublishSubject<Void>()
private let bag = DisposeBag()
class func instanceFromNib() -> RightButtonItemView
return UINib(nibName: "NotificationView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! RightButtonItemView
override func awakeFromNib()
rightButtonButton.rx.tap
.bind(to: performEventSegue)
.disposed(by: bag)
-- 更新--
我想到了这个解决方案,我认为它更好。您根本不需要主题:
class RightButtonItemView: UIView
@IBOutlet weak var rightButtonButton: UIButton!
var performEventSegue: Observable<Void>
return rightButtonButton.rx.tap.asObservable()
【讨论】:
以上是关于如何在按钮点击时观察 PublishSubject的主要内容,如果未能解决你的问题,请参考以下文章
RxJava2.1.0:在不同线程上订阅时未调用 PublishSubject onNext