0

i have initialized an empty observable like this:

var subCategories = Observable<[String]>.empty()

How can i check if the observable is empty or not? I would like to show a "empty view" to the user if the observable is empty else show the data in tableview.

duan
  • 8,515
  • 3
  • 48
  • 70
Frankenxtein
  • 483
  • 7
  • 18
  • 1
    Empty Observable refers to an Observable emit a single `onComplete`. The use-case you described should be implemented with an Observable which emits `[String]` with length from 0 to n. – duan Sep 18 '19 at 13:09

3 Answers3

1

create a bool Observable to show/hide your emptyView:

let hideEmptyView = subCategories.map{!$0.isEmpty}

then bind this hideEmptyView Bool Observable to yourEmptyView.rx.isHidden

Behrad Kazemi
  • 302
  • 1
  • 10
0

You have to use filter on the Observable :

viewModel.filteredUsers.asObservable()
        .filter({ [weak self] array in
            guard let self = self else {return true}
            
            if array.isEmpty {
                self.emptyListContainer.alpha = 1
                self.tableView.alpha = 0
            } else {
                self.emptyListContainer.alpha = 0
                self.tableView.alpha = 1
                
            }
            return true
        })
        .bind(to: tableView.rx.items(cellIdentifier: "ContactsTableViewCell", cellType: ContactsTableViewCell.self)) { (row, user, cell) in
        cell.titleLbl.text = user.name
    }
    .disposed(by: disposeBag)
BabakHSL
  • 622
  • 1
  • 8
  • 18
-1

use a BehaviourRelay other than Observable.

import RxCocoa
import RxSwift

var subCategories = BehaviorRelay<[String]>(value: [])
let emptyView = UIStackView()

func addObservers() {
    subCategories.asObservable().subscribe { _ in
        self.emptyView.isHidden = !self.subCategories.value.isEmpty
    }.disposed(by: DisposeBag())
}
Pramodya Abeysinghe
  • 1,098
  • 17
  • 13