MVVM and RxSwift for Search Screen - ios

In purpose of education MVVM and RxSwift I want to build simple search screen, which will have a table view and a search bar. When user types something into the search bar I will show what he have in this table. Sounds pretty simple, but I can't find any tutorial which suits me.
I have already written all code in view controller, I just can't understand have to observe search text changes and then call database method, which will filter items by search text.
Some code, which I already have.
My ViewController
import Foundation
import UIKit
import RxSwift
import RxCocoa
class PlaceSearchViewController: UIViewController {
//MARK: -
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var tableView: UITableView!
//MARK: - Dependencies
private var viewModel: PlaceSearchViewModel!
private let disposeBag = DisposeBag()
//MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
viewModel = PlaceSearchViewModel()
addBindsToViewModel(viewModel)
}
//MARK: - Rx
private func addBindsToViewModel(viewModel: PlaceSearchViewModel) {
searchBar.rx_text.bindTo(viewModel.searchTextObservable)
viewModel.placesObservable.bindTo(tableView.rx_itemsWithCellFactory) {
(tableView: UITableView, index, place: Place) in
let indexPath = NSIndexPath(forItem: index, inSection: 0)
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as PlaceCell
cell.configureWithObject(place)
return cell
}
.addDisposableTo(disposeBag)
tableView.rx_contentOffset
.subscribe { _ in
if self.searchBar.isFirstResponder() {
_ = self.searchBar.resignFirstResponder()
}
}
.addDisposableTo(disposeBag)
}
}
And my view model:
import Foundation
import RxSwift
import RxCocoa
class PlaceSearchViewModel {
//MARK: - Dependecies
private let disposeBag = DisposeBag()
//MARK: - Model
private let placesObservable: Observable<[Place]>
var searchTextObservable = Variable<String>("")
//MARK: - Set up
init() {
placesObservable = searchTextObservable.asObservable()
//wait 0.3 s after the last value to fire a new value
.debounce(0.3, scheduler: MainScheduler.instance)
//only fire if the value is different than the last one
.distinctUntilChanged()
//convert Observable<String> to Observable<[Place]>
.flatMapLatest { searchString -> Observable<[Place]> in
// some code here which I can't write.
}
//make sure all subscribers use the same exact subscription
.shareReplay(1)
}
}
Also, I have method [DataBase searchPlaces:searchText] which returns array of places - [Place]. I can't understand where and how place it in flatMapLatest of my ViewModel.

I create reactive wrapper for my DataBase by creating Observable<[Place]>.
This is my code
placesObservable = searchTextObservable.asObservable()
//wait 0.3 s after the last value to fire a new value
.debounce(0.0, scheduler: MainScheduler.instance)
//only fire if the value is different than the last one
.distinctUntilChanged()
//convert Observable<String> to Observable<Weather>
.flatMapLatest { searchString -> Observable<[AnyObject]> in
return TPReactiveDatabase.sharedInstance.searchPlacesByTitle(searchString)
}
//make sure all subscribers use the same exact subscription
.shareReplay(1)
And wrapper method searchPlacesByTitle
class TPReactiveDatabase: NSObject {
static let sharedInstance = TPReactiveDatabase()
// MARK: - Reactive Place database
func searchPlacesByTitle(title: String) -> Observable<[AnyObject]> {
return Observable.create { observer in
var places = [AnyObject]()
if (title.characters.count > 0) {
places = DBAccessKit.searchPlacesByTitle(title)
}
observer.on(.Next(places))
observer.on(.Completed)
return AnonymousDisposable {
}
}
}
}

Related

How to bind data from viewModel in view with rxSwift and Moya?

I'm trying to create an app to get some news from an API and i'm using Moya, RxSwift and MVVM.
This is my ViewModel:
import Foundation
import RxSwift
import RxCocoa
public enum NewsListError {
case internetError(String)
case serverMessage(String)
}
enum ViewModelState {
case success
case failure
}
protocol NewsListViewModelInput {
func viewDidLoad()
func didLoadNextPage()
}
protocol MoviesListViewModelOutput {
var newsList: PublishSubject<NewsList> { get }
var error: PublishSubject<String> { get }
var loading: PublishSubject<Bool> { get }
var isEmpty: PublishSubject<Bool> { get }
}
protocol NewsListViewModel: NewsListViewModelInput, MoviesListViewModelOutput {}
class DefaultNewsListViewModel: NewsListViewModel{
func viewDidLoad() {
}
func didLoadNextPage() {
}
private(set) var currentPage: Int = 0
private var totalPageCount: Int = 1
var hasMorePages: Bool {
return currentPage < totalPageCount
}
var nextPage: Int {
guard hasMorePages else { return currentPage }
return currentPage + 1
}
private var newsLoadTask: Cancellable? { willSet { newsLoadTask?.cancel() } }
private let disposable = DisposeBag()
// MARK: - OUTPUT
let newsList: PublishSubject<NewsList> = PublishSubject()
let error: PublishSubject<String> = PublishSubject()
let loading: PublishSubject<Bool> = PublishSubject()
let isEmpty: PublishSubject<Bool> = PublishSubject()
func getNewsList() -> Void{
print("sono dentro il viewModel!")
NewsDataService.shared.getNewsList()
.subscribe { event in
switch event {
case .next(let progressResponse):
if progressResponse.response != nil {
do{
let json = try progressResponse.response?.map(NewsList.self)
print(json!)
self.newsList.onNext(json!)
}
catch _ {
print("error try")
}
} else {
print("Progress: \(progressResponse.progress)")
}
case .error( _): break
// handle the error
default:
break
}
}
}
}
This is my ViewController, where xCode give me the following error when i try to bind to tableNews:
Expression type 'Reactive<_>' is ambiguous without more context
import UIKit
import RxSwift
import RxCocoa
class ViewController: UIViewController {
#IBOutlet weak var tableNews: UITableView!
let viewModel = DefaultNewsListViewModel()
var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
}
private func setupBindings() {
viewModel.newsList.bind(to: tableNews.rx.items(cellIdentifier: "Cell")) {
(index, repository: NewsList, cell) in
cell.textLabel?.text = repository.name
cell.detailTextLabel?.text = repository.url
}
.disposed(by: disposeBag)
}
}
This is the service that get data from API:
import Moya
import RxSwift
struct NewsDataService {
static let shared = NewsDataService()
private let disposable = DisposeBag()
private init() {}
fileprivate let newsListProvider = MoyaProvider<NewsService>()
func getNewsList() -> Observable<ProgressResponse> {
self.newsListProvider.rx.requestWithProgress(.readNewsList)
}
}
I'm new at rxSwift, I followed some documentation but i'd like to know if i'm approaching in the right way. Another point i'd like to know is how correctly bind my tableView to viewModel.
Thanks for the support.
As #FabioFelici mentioned in the comments, UITableView.rx.items(cellIdentifier:) is expecting to be bound to an Observable that contains an array of objects but your NewsListViewModel.newsList is an Observable<NewsList>.
This means you either have to extract the array out of NewsList (assuming it has one) through a map. As in newsList.map { $0.items }.bind(to:...
Also, your MoviesListViewModelOutput should not be full of Subjects, rather it should contain Observables. And I wouldn't bother with the protocols, struts are fine.
Also, your view model is still very imperative, not really in an Rx style. A well constructed Rx view model doesn't contain functions that are repeatedly called. It just has a constructor (or is itself just a single function.) You create it, bind to it and then you are done.

Best practice for binding controls in UITableViewCell to ViewModel using RxSwift

I'm in the process of migrating an existing app using MVC that makes heavy use of the delegation pattern to MVVM using RxSwift and RxCocoa for data binding.
In general each View Controller owns an instance of a dedicated View Model object. Let's call the View Model MainViewModel for discussion purposes. When I need a View Model that drives a UITableView, I generally create a CellViewModel as a struct and then create an observable sequence that is converted to a driver that I can use to drive the table view.
Now, let's say that the UITableViewCell contains a button that I would like to bind to the MainViewModel so I can then cause something to occur in my interactor layer (e.g. trigger a network request). I'm not sure what is the best pattern to use in this situation.
Here is a simplified example of what I've started out with (see 2 specific question below code example):
Main View Model:
class MainViewModel {
private let buttonClickSubject = PublishSubject<String>() //Used to detect when a cell button was clicked.
var buttonClicked: AnyObserver<String> {
return buttonClickSubject.asObserver()
}
let dataDriver: Driver<[CellViewModel]>
let disposeBag = DisposeBag()
init(interactor: Interactor) {
//Prepare the data that will drive the table view:
dataDriver = interactor.data
.map { data in
return data.map { MyCellViewModel(model: $0, parent: self) }
}
.asDriver(onErrorJustReturn: [])
//Forward button clicks to the interactor:
buttonClickSubject
.bind(to: interactor.doSomethingForId)
.disposed(by: disposeBag)
}
}
Cell View Model:
struct CellViewModel {
let id: String
// Various fields to populate cell
weak var parent: MainViewModel?
init(model: Model, parent: MainViewModel) {
self.id = model.id
//map the model object to CellViewModel
self.parent = parent
}
}
View Controller:
class MyViewController: UIViewController {
let viewModel: MainViewModel
//Many things omitted for brevity
func bindViewModel() {
viewModel.dataDriver.drive(tableView.rx.items) { tableView, index, element in
let cell = tableView.dequeueReusableCell(...) as! TableViewCell
cell.bindViewModel(viewModel: element)
return cell
}
.disposed(by: disposeBag)
}
}
Cell:
class TableViewCell: UITableViewCell {
func bindViewModel(viewModel: MyCellViewModel) {
button.rx.tap
.map { viewModel.id } //emit the cell's viewModel id when the button is clicked for identification purposes.
.bind(to: viewModel.parent?.buttonClicked) //problem binding because of optional.
.disposed(by: cellDisposeBag)
}
}
Questions:
Is there a better way of doing what I want to achieve using these technologies?
I declared the reference to parent in CellViewModel as weak to avoid a retain cycle between the Cell VM and Main VM. However, this causes a problem when setting up the binding because of the optional value (see line .bind(to: viewModel.parent?.buttonClicked) in TableViewCell implemenation above.
The solution here is to move the Subject out of the ViewModel and into the ViewController. If you find yourself using a Subject or dispose bag inside your view model, you are probably doing something wrong. There are exceptions, but they are pretty rare. You certainly shouldn't be doing it as a habit.
class MyViewController: UIViewController {
var tableView: UITableView!
var viewModel: MainViewModel!
private let disposeBag = DisposeBag()
func bindViewModel() {
let buttonClicked = PublishSubject<String>()
let input = MainViewModel.Input(buttonClicked: buttonClicked)
let output = viewModel.connect(input)
output.dataDriver.drive(tableView.rx.items) { tableView, index, element in
var cell: TableViewCell! // create and assign
cell.bindViewModel(viewModel: element, buttonClicked: buttonClicked.asObserver())
return cell
}
.disposed(by: disposeBag)
}
}
class TableViewCell: UITableViewCell {
var button: UIButton!
private var disposeBag = DisposeBag()
override func prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
}
func bindViewModel<O>(viewModel: CellViewModel, buttonClicked: O) where O: ObserverType, O.Element == String {
button.rx.tap
.map { viewModel.id } //emit the cell's viewModel id when the button is clicked for identification purposes.
.bind(to: buttonClicked) //problem binding because of optional.
.disposed(by: disposeBag)
}
}
class MainViewModel {
struct Input {
let buttonClicked: Observable<String>
}
struct Output {
let dataDriver: Driver<[CellViewModel]>
}
private let interactor: Interactor
init(interactor: Interactor) {
self.interactor = interactor
}
func connect(_ input: Input) -> Output {
//Prepare the data that will drive the table view:
let dataDriver = interactor.data
.map { data in
return data.map { CellViewModel(model: $0) }
}
.asDriver(onErrorJustReturn: [])
//Forward button clicks to the interactor:
_ = input.buttonClicked
.bind(to: interactor.doSomethingForId)
// don't need to put in dispose bag because the button will emit a `completed` event when done.
return Output(dataDriver: dataDriver)
}
}
struct CellViewModel {
let id: String
// Various fields to populate cell
init(model: Model) {
self.id = model.id
}
}
you can use this RxReusable.
this is Rx extension of UITableViewCell, UICollectionView…

How do you communicate between a UIViewController and its child UIView using MVVM and RxSwift events?

I'm using MVVM, Clean Architecture and RxSwift in my project. There is a view controller that has a child UIView that is created from a separate .xib file on the fly (since it is used in multiple scenes). Thus there are two viewmodels, the UIViewController's view model and the UIView's. Now, there is an Rx event in the child viewmodel that should be observed by the parent and then it will call some of its and its viewmodel's functions. The code is like this:
MyPlayerViewModel:
class MyPlayerViewModel {
var eventShowUp: PublishSubject<Void> = PublishSubject<Void>()
var rxEventShowUp: Observable<Void> {
return eventShowUp
}
}
MyPlayerView:
class MyPlayerView: UIView {
var viewModel: MyPlayerViewModel?
setup(viewModel: MyPlayerViewModel) {
self.viewModel = viewModel
}
}
MyPlayerSceneViewController:
class MyPlayerSceneViewController: UIViewController {
#IBOutlet weak var myPlayerView: MyPlayerView!
#IBOutlet weak var otherView: UIView!
var viewModel: MyPlayerSceneViewModel
fileprivate var disposeBag : DisposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
self.myPlayerView.viewModel.rxEventShowUp.subscribe(onNext: { [weak self] in
self?.viewModel.doOnShowUp()
self?.otherView.isHidden = true
})
}
}
As you can see, currently, I am exposing the myPlayerView's viewModel to the public so the parent can observe the event on it. Is this the right way to do it? If not, is there any other suggestion about the better way? Thanks.
In general, nothing bad to expose view's stuff to its view controller but do you really need two separate view models there? Don't you mix viewModel and model responsibilities?
Some thoughts:
Model shouldn't subclass UIView.
You should avoid creating own subjects in a view model. It doesn't create events by itself, it only processes input and exposes results.
I encourage you to get familiar with Binder and Driver.
Here is the code example:
struct PlayerModel {
let id: Int
let name: String
}
class MyPlayerSceneViewModel {
struct Input {
let eventShowUpTrigger: Observable<Void>
}
struct Output {
let someUIAction: Driver<PlayerModel>
}
func transform(input: Input) -> Output {
let someUIAction = input.eventShowUpTrigger
.flatMapLatest(fetchPlayerDetails) // Transform input
.asDriver(onErrorJustReturn: PlayerModel(id: -1, name: "unknown"))
return Output(someUIAction: someUIAction)
}
private func fetchPlayerDetails() -> Observable<PlayerModel> {
return Observable.just(PlayerModel(id: 1, name: "John"))
}
}
class MyPlayerView: UIView {
var eventShowUp: Observable<Void> {
return Observable.just(()) // Expose some UI trigger
}
var playerBinding: Binder<PlayerModel> {
return Binder(self) { target, player in
target.playerNameLabel.text = player.name
}
}
let playerNameLabel = UILabel()
}
class MyPlayerSceneViewController: UIViewController {
#IBOutlet weak var myPlayerView: MyPlayerView!
private var viewModel: MyPlayerSceneViewModel!
private var disposeBag: DisposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
setupBindings()
}
private func setupBindings() {
let input = MyPlayerSceneViewModel.Input(eventShowUpTrigger: myPlayerView.eventShowUp)
let output = viewModel.transform(input: input)
// Drive manually
output
.someUIAction
.map { $0.name }
.drive(myPlayerView.playerNameLabel.rx.text)
.disposed(by: disposeBag)
// or to exposed binder
output
.someUIAction
.drive(myPlayerView.playerBinding)
.disposed(by: disposeBag)
}
}

Dynamically filter results with RxSwift and Realm

I have a very simple project, where I want to dynamically filter content in UITableView regarding pressed index in UISegmentedControl. I'm using MVVM with RxSwift, Realm and RxDataSources. So my problem, that if I want to update content in UITableView I need to create 'special' DisposeBag, only for that purposes, and on each selection in UISegmentedControl nil it and create again. Only in this case, if I'm understand right, subscription is re-newed, and UITableView displays new results from Realm.
So is there any better way to do such operation? Without subscribing every time, when I switch tab in UISegmentedControl. Here's my code:
//ViewController
class MyViewController : UIViewController {
//MARK: - Props
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var segmentedControl: UISegmentedControl!
let dataSource = RxTableViewSectionedReloadDataSource<ItemsSection>()
let disposeBag = DisposeBag()
var tableViewBag: DisposeBag!
var viewModel: MyViewModel = MyViewModel()
//MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.setupRxTableView()
}
//MARK: - Setup observables
fileprivate func setupRxTableView() {
dataSource.configureCell = { ds, tv, ip, item in
let cell = tv.dequeueReusableCell(withIdentifier: "ItemCell") as! ItemTableViewCell
return cell
}
bindDataSource()
segmentedControl.rx.value.asDriver()
.drive(onNext: {[weak self] index in
guard let sSelf = self else { return }
switch index {
case 1:
sSelf.bindDataSource(filter: .active)
case 2:
sSelf.bindDataSource(filter: .groups)
default:
sSelf.bindDataSource()
}
}).disposed(by: disposeBag)
}
private func bindDataSource(filter: Filter = .all) {
tableViewBag = nil
tableViewBag = DisposeBag()
viewModel.populateApplying(filter: filter)
}).bind(to: self.tableView.rx.items(dataSource: dataSource))
.disposed(by: tableViewBag)
}
}
//ViewModel
class MyViewModel {
func populateApplying(filter: Filter) -> Observable<[ItemsSection]> {
return Observable.create { [weak self] observable -> Disposable in
guard let sSelf = self else { return Disposables.create() }
let realm = try! Realm()
var items = realm.objects(Item.self).sorted(byKeyPath: "date", ascending: false)
if let predicate = filter.makePredicate() { items = items.filter(predicate) }
let section = [ItemsSection(model: "", items: Array(items))]
observable.onNext(section)
sSelf.itemsToken = items.addNotificationBlock { changes in
switch changes {
case .update(_, _, _, _):
let section = [ItemsSection(model: "", items: Array(items))]
observable.onNext(section)
default: break
}
}
return Disposables.create()
}
}
}
Don't recall if this is breaking MVVM off the top of my head, but would Variable not be what you're looking for?
Variable<[TableData]> data = new Variable<[TableData]>([])
func applyFilter(filter: Predicate){
data.value = items.filter(predicate) //Any change to to the value will cause the table to reload
}
and somewhere in the viewController
viewModel.data.rx.asDriver().drive
(tableView.rx.items(cellIdentifier: "ItemCell", cellType: ItemTableViewCell.self))
{ row, data, cell in
//initialize cells with data
}

How to configure a Bool Stream in RxSwift

I am willing to force a reload of a collectionView when new content is fetched from a web-service while using RxSwift. I can't figure out why I don't receive an event on newContent with the following code when my onComplete closure is properly called.
class ListingView : UIView {
var newContentStream: Observable<Bool>?
let disposeBag = DisposeBag()
#IBOutlet weak var collectionView: UICollectionView!
weak var viewModel: ListingViewModel?
func bind(viewModel: ListingViewModel) {
self.viewModel = viewModel
}
func configure() {
guard let viewModel = self.viewModel else { return }
self.newContentStream = viewModel.newContent.asObservable()
self.newContentStream!.subscribeNext { _ in
self.collectionView.reloadData()
}
.addDisposableTo(self.disposeBag)
}
}
and then within my viewModel:
class ListingViewModel {
let dataSource = ListingViewDataSoure()
var newContent = Variable(false)
func mount() {
let onComplete : ([item]? -> Void) = { [weak self] items in
self?.dataSource.items = items
self?.newContent = Variable(true)
}
guard let URL = API.generateURL() else { return }
Requestor.fetchAll(onComplete, fromURL: URL)
}
}
It's because self?.newContent = Variable(true) is replacing the newContent with an entirely new Variable, after you've already subscribed to the original here:
self.newContentStream = viewModel.newContent.asObservable()
self.newContentStream!.subscribeNext { ......
That subscription in your UIView is now listening to an Observable that no one is ever going to be sending a Next event on.
Instead, you should be sending out a Next event on the current (and only) newContent Variable/Observable:
self?.newContent.value = true
You could fix it and continue to use a newContent Variable and a reloadData call, however, I wouldn't recommend doing it like this. Instead, check out RxDataSources.

Resources