0

I'm trying to implement compactMap on RxSwift but it seems like is never executed.

Here is my code:

class MyClass{

    var disposeBag = DisposeBag()
    let subject = BehaviorRelay(value: 1)

    func doSomething() {
        Observable.from(optional: subject).compactMap{  $0

        }.subscribe( onNext:{
            print($0)
        }).disposed(by: disposeBag)
        subject.accept(2)
        subject.accept(4)
        subject.accept(5)
        subject.accept(8)
    }
}

When I change the value on subject the compactMap never gets called. Why not?

shim
  • 9,289
  • 12
  • 69
  • 108
user2924482
  • 8,380
  • 23
  • 89
  • 173

1 Answers1

1

You are creating an Observable<BehaviorRelay<Int>> by using the from operator which only emits one value (the behavior relay itself) and then completes. The accept calls are being ignored because nothing is subscribing to the behavior relay itself.

I think you need to step back and figure out what you are trying to accomplish, and then read the documentation on the operators to find one that does what you need.

Daniel T.
  • 32,821
  • 6
  • 50
  • 72
  • This does provide the answer, in the first part. I think you're being too bent on the comment where this does not actually make sense to notice that the first part says what's the actual behavior of the code posted. – Adis Dec 04 '19 at 10:08
  • I removed the critique of the code and expanded on the answer. – Daniel T. Dec 05 '19 at 00:18