Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to handle RefreshControl in iOS #20

Open
onmyway133 opened this issue May 4, 2017 · 0 comments
Open

How to handle RefreshControl in iOS #20

onmyway133 opened this issue May 4, 2017 · 0 comments

Comments

@onmyway133
Copy link
Owner

onmyway133 commented May 4, 2017

The other day I was doing refresh control, and I saw this Swift Protocols with Default Implementations as UI Mixins

extension Refreshable where Self: UIViewController
{
    /// Install the refresh control on the table view
    func installRefreshControl()
    {
        let refreshControl = UIRefreshControl()
        refreshControl.tintColor = .primaryColor
        refreshControl.addTarget(self, action: #selector(handleRefresh(_:)), for: .valueChanged)
        self.refreshControl = refreshControl
        
        if #available(iOS 10.0, *)
        {
            tableView.refreshControl = refreshControl
        }
        else
        {
            tableView.backgroundView = refreshControl
        }
    }
}

Protocol extension is cool but somehow I'm not a fan of it. I always consider composition first, to extract the specific task to one entity that does that well. It looks like this

class RefreshHandler: NSObject {
  let refresh = PublishSubject<Void>()
  let refreshControl = UIRefreshControl()

  init(view: UIScrollView) {
    super.init()
    view.addSubview(refreshControl)
    refreshControl.addTarget(self, action: #selector(refreshControlDidRefresh(_: )), for: .valueChanged)
  }

  // MARK: - Action

  func refreshControlDidRefresh(_ control: UIRefreshControl) {
    refresh.onNext(())
  }

  func end() {
    refreshControl.endRefreshing()
  }
}

It is a bit Rx, we can use block if we like, but the idea is we can declare this RefreshHandler and use it everywhere we want

refreshHandler = RefreshHandler(view: scrollView)

refreshHandler.refresh
      .startWith(())
      .bindTo(viewModel.input.fetch)
      .addDisposableTo(bag)
@onmyway133 onmyway133 changed the title Handle refreshControl How to handle RefreshControl in iOS May 23, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant