beginner992
beginner992

Reputation: 719

RxSwift and duplicated array data

I have a ViewController where an array of data is displayed (FavoriteViewController). In the another one ViewController I can select the objects I want to add to the list from the previous ViewController, but there is a problem. If I come back from the second ViewController, the data is duplicated. Every time I go back to the ViewController with the Array mentioned, I refresh the data for the most current data and this causes duplication. How can I fix it?

FavoriteViewController:

class FavoriteViewController: UIViewController {

@IBOutlet weak var stationsTableView: UITableView!
private var disposeBag = DisposeBag()
private var viewModel = FavoriteViewModel()


override func viewDidLoad() {
    super.viewDidLoad()
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.hidesBottomBarWhenPushed = true
    
    stationsTableView.rx.setDelegate(self).disposed(by: disposeBag)
    bindTableView()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    self.hidesBottomBarWhenPushed = false
    stationsTableView.dataSource = nil
    stationsTableView.delegate = nil
    
}

override func viewDidDisappear(_ animated: Bool) {
   disposeBag = DisposeBag()
}
    
func bindTableView() {
    self.viewModel.stationItems.asObservable().distinctUntilChanged().bind(to: stationsTableView.rx.items(cellIdentifier: "cell", cellType: FavoriteTableViewCell.self)) { (row,item,cell) in
        cell.cellStation = item
    }.disposed(by: disposeBag)
    
    stationsTableView.rx.modelSelected(StationItem.self).subscribe(onNext: { item in
        print("SelectedItem: \(item)")
    }).disposed(by: disposeBag)
    
    deleteStation()
    
    viewModel.fetchSavedStationItems()
}

FavoriteViewModel:

class FavoriteViewModel: ObservableObject {

private let apiService : APIServiceProtocol
private let persistenceService: PersistenceServiceProtocol
public let stationItems = BehaviorSubject<[StationItem]>(value: [])
var itemsList = [StationItem]()

init(apiService: APIServiceProtocol = APIService(), persistenceService: PersistenceServiceProtocol = PersistenceService()) {
    self.apiService = apiService
    self.persistenceService = persistenceService
}

func fetchSavedStationItems() {
    do {
        itemsList += try persistenceService.fetchStationItems()
        self.stationItems.onNext(itemsList)
    } catch {
        print("ERROR fetchedSavedStationItems FavoriteViewModel")
    }
}

Upvotes: 0

Views: 207

Answers (1)

aiwiguna
aiwiguna

Reputation: 2922

because you always append your array, in fetchSavedStationItems()

itemsList += try persistenceService.fetchStationItems()

try clear the array before append it

itemsList.removeAll()
itemsList += try persistenceService.fetchStationItems()

Upvotes: 1

Related Questions