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

binding view with view model #2

Closed
lenaios opened this issue Aug 1, 2021 · 1 comment
Closed

binding view with view model #2

lenaios opened this issue Aug 1, 2021 · 1 comment
Assignees

Comments

@lenaios
Copy link
Owner

lenaios commented Aug 1, 2021

  • main, soup, side 카테고리(section)의 순서를 보장할 수 있어야 한다.
  • 데이터를 받아온 section만 reload 한다.
@lenaios
Copy link
Owner Author

lenaios commented Aug 8, 2021

[1차] tableView.rx.items를 활용해서 바인딩

viewModel.subject
  .bind(to: tableView.rx.items(
    cellIdentifier: "Cell",
    cellType: UITableViewCell.self)) { index, item, cell in
      cell.textLabel?.text = item.detailHash
  }.disposed(by: disposeBag)

[2차] tableView.rx.items는 section이 하나 이상일 때는 사용하기 어렵다. RxDataSources 활용하는 방법으로 변경

private let dataSource = RxTableViewSectionedReloadDataSource<SectionOfData>(
  configureCell: { (_, tableView, indexPath, element) in
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
    cell.textLabel?.text = element.title
    return cell
  },
  titleForHeaderInSection: { dataSource, sectionIndex in
    return dataSource[sectionIndex].header
  }
)

[3차] main, soup, side의 순서(section)를 보장하기 위해 Category 속성을 section model에 추가하고,
정렬된 sections 데이터를 방출하도록 개선 -> 순서를 보장하기 위해 매번 전체 table이 reload 되어야 하는 구조

enum Category: Int {
  case main = 1
  case soup
  case side
}

private var sections: [SectionOfData] = [] {
  didSet {
    sections.sort { $0.category < $1.category }
  }
}

[4차] 전체 section 대신, 먼저 받아온 데이터(main, soup, side)만 reload 할 수 없을까?
IndexSet 이벤트를 방출하고, 해당 index의 section을 reload 하도록 변경
이 때, 메인 큐에 sync로 수행하지 않으면 crash가 발생한다.

// in view model
var subject = PublishSubject<IndexSet>()

// in controller
viewModel.subject
  .subscribe(onNext: { data in
    DispatchQueue.main.sync {
      self.tableView.reloadSections(data, with: .automatic)
    }
  })
  .disposed(by: disposeBag)

회고

  • RxDataSources를 사용했더라도, SectionOfData를 미리 생성해두고 각 section에 해당하는 data가 왔을 때 이벤트를 방출하면 의도한대로 구현 가능하지 않았을까

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant