Frankenxtein
Frankenxtein

Reputation: 493

How to check if an observable is empty in RXSwift?

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.

Upvotes: 0

Views: 3484

Answers (4)

Syed Ali Salman
Syed Ali Salman

Reputation: 2915

one line solution is to have something like this

yourBehaviourRelay.map{$0.isEmpty}.bind(to: yourView.rx.isHidden).disposed(by: DisposeBag())

Upvotes: 0

BabakHSL
BabakHSL

Reputation: 782

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)

Upvotes: 1

Pramodya Abeysinghe
Pramodya Abeysinghe

Reputation: 1210

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())
}

Upvotes: -1

Behrad Kazemi
Behrad Kazemi

Reputation: 402

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

Upvotes: 1

Related Questions