RXswift常见使用场景

在项目中常见的使用功能

1.下面样例中我们将 textField 里输入的内容实时地显示到控制台中。时时监听输入的内容 (比较常见功能)(同时监听多个 textField 内容的变化不列举)


        //当文本框内容改变时,将内容输出到控制台上

        textField.rx.text.orEmpty.asObservable()

            .subscribe(onNext: {

                print("您输入的是:\($0)")

            })

            .disposed(by:disposeBag)

2.监听输入框的输入内容数量

        //当文本框内容改变

        letinput = textField.rx.text.orEmpty.asDriver()// 将普通序列转换为 Driver

            .throttle(0.3) //在主线程中操作,0.3秒内值若多次改变,取最后一次


        //内容绑定到文本标签中 map中的数据类型需要跟drive中填充的类型一致 

        input.map{"当前字数:\($0.count)"}

            .drive(label.rx.text)

            .disposed(by:disposeBag)

        //根据内容字数决定按钮是否可用

        input.map{ $0.count>5}

            .drive(button.rx.isEnabled)

            .disposed(by:disposeBag)

3.button使用 swift\UISegmentedControl\slider\也是类似

    //将按钮的响应事件放入到自己的懒加载中 起到代码解耦的作用 也更加直观

    lazyvarbutton:UIButton= {

        letbutton =UIButton(type: .custom)

        button.setTitle("测试按钮方法", for: .normal)

        button.titleLabel?.font=UIFont.systemFont(ofSize:18)

        button.backgroundColor = UIColor.yellow

        button.setTitleColor(UIColor.white, for:.normal)

        //按钮点击响应

        button.rx.tap.bind{ [weakself]in

            self?.showMessage("按钮被点击")

        }.disposed(by:disposeBag)

        returnbutton

    }()

4.双向绑定将model中的数据跟UI界面展示进行绑定,适用于点赞\评论等时时变化的数据进行UI刷新跟数据同步

userVM.username.asObservable().bind(to:textField.rx.text).disposed(by:disposeBag)textField.rx.text.orEmpty.bind(to:userVM.username).disposed(by:disposeBag)

5.通知的用法

//发送通知letnotificationName=Notification.Name(rawValue:"DownloadImageNotification")NotificationCenter.default.post(name:notificationName,object:self,userInfo:["value1":"hangge.com","value2":12345])

//接收通知letnotificationName=Notification.Name(rawValue:"DownloadImageNotification")_=NotificationCenter.default.rx.notification(notificationName).takeUntil(self.rx.deallocated)//页面销毁自动移除通知监听.subscribe(onNext:{notificationin//获取通知数据letuserInfo=notification.userInfoas![String:AnyObject]letvalue1=userInfo["value1"]as!Stringletvalue2=userInfo["value2"]as!Intprint("\(name)获取到通知,用户数据是[\(value1),\(value2)]")//等待3秒sleep(3)print("\(name)执行完毕")})

这个用法的好处就是当页面注销掉之后通知会跟随回收,防止内存泄漏

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 概述 RxSwift顾名思义是Swift的一种框架,您或许曾经听说过「响应式编程」(Reactive Progra...
    Mr大喵喵阅读 1,909评论 3 4
  • //PublishSubject -> 会发送订阅者从订阅之后的事件序列 PublishSubjectlet se...
    zidon阅读 1,603评论 0 3
  • 一、响应式编程 1.1、响应式编程(Reactive Programming,简称RP)响应式编程是一种编程范式,...
    IIronMan阅读 1,047评论 0 3
  • 什么是响应式编程 响应式编程是一种和事件流有关的编程模式,关注导致状态值改变的行为事件,一系列事件组成了事件流。 ...
    海边的1984_阅读 856评论 1 2
  • 一、Observable二、Observer三、Subject四、Operator五、Disposable六、Sc...
    yahibo阅读 706评论 2 4