今是昨非

今是昨非

日出江花红胜火,春来江水绿如蓝

RxSwift Usage

RxSwift Usage Memo#

This is a record of commonly used methods in RxSwift.

Implementing Search with RxSwift#

The purpose of distinctUntilChanged is to prevent new events from being generated for adjacent duplicate events. Therefore, using distinctUntilChanged in a search ensures that only different strings are triggered for each search, and it also ensures that only one search is triggered after input stops.

The difference between throttle and debounce:

  • throttle calls every fixed interval of time.
  • debounce calls after a certain number of seconds after the event stops.

Therefore, if you need to implement searching while typing, use throttle.


    fileprivate func configureSearch() {
      searchBar.rx.text
            .orEmpty
            .throttle(1.0, scheduler: MainScheduler.instance)
            .distinctUntilChanged()
            .subscribe { [unowned self] (query) in
                
            }.disposed(by: disposeBag)
    }

And if you need to implement searching after input stops, use debounce.


    fileprivate func configureSearch() {
      searchBar.rx.text
            .orEmpty
            .distinctUntilChanged()
            .debounce(0.5, scheduler: MainScheduler.instance)
            .subscribe { [unowned self] (query) in
                
            }.disposed(by: disposeBag)
    }

Implementing Clicks with RxSwift#


button.rx.tap
    .subscribe(onNext: {
        print("button Tapped")
    })
    .disposed(by: disposeBag)

Implementing Delegates with RxSwift#

scrollView Delegate#


override func viewDidLoad() {
    super.viewDidLoad()

    scrollView.rx.contentOffset
        .subscribe(onNext: { contentOffset in
            print("contentOffset: \(contentOffset)")
        })
        .disposed(by: disposeBag)
}

tableView Delegate#


fileprivate func setupVM() {
    vm.dataList
        .bind(to: tableView.rx.items(cellIdentifier: Cell.CellIdentifier, cellType: Cell.self)) { _, model, cell in
            cell.model = model
        }
        .disposed(by: disposeBag)
    
    Observable
        .zip(tableView.rx.itemSelected, tableView.rx.modelSelected(CellModel.self))
        .subscribe(onNext: { [weak self] indexPath, item in
            self?.handleSelectItem(at: indexPath, model: item)
        })
        .disposed(by: disposeBag)
    
    vm.pageNum
        .subscribe(onNext: { [weak self] pageNum in
            self?.loadData(pageNum)
        })
        .disposed(by: disposeBag)
    
    vm.isLastPage
        .subscribe(onNext: { [weak self] isLastPage in
            self?.tableView.mj_header?.endRefreshing()
            if isLastPage {
                self?.tableView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                self?.tableView.mj_footer?.endRefreshing()
            }
        })
        .disposed(by: disposeBag)
}

Implementing Notifications with RxSwift#


override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.rx
        .notification(.UIApplicationWillEnterForeground)
        .subscribe(onNext: { (notification) in
            print("Application Will Enter Foreground")
        })
        .disposed(by: disposeBag)
}

Integrating Network Requests with RxSwift#

flatMapLatest is used to handle situations where multiple tasks have dependencies, to avoid callback hell.


/// Get user information by username and password
API.token(username: "beeth0ven", password: "987654321")
    .flatMapLatest(API.userInfo)
    .subscribe(onNext: { userInfo in
        print("Successfully obtained user information: \(userInfo)")
    }, onError: { error in
        print("Failed to obtain user information: \(error)")
    })
    .disposed(by: disposeBag)

zip is used to send multiple requests simultaneously and process them only after all requests are completed.

combineLatest is used to send multiple requests simultaneously, and each request triggers the method for handling events when it is completed.

References:

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.