user6902806
user6902806

Reputation: 280

RxSwift: disposed(by:) weirdness

So the code below compiles with the errror

var doneSubscription: Disposable = item.doneSubjectObservable
        .debug("doneSubscriptions")
        .subscribe(
            onNext: {
                done in self.validateDone(done: done, item: item)
        }).disposed(by: disposeBag)

Value of type '()' does not conform to specified type 'Disposable' on the line .disposed(by: disposeBag)

But I can do this without error:

var doneSubscription: Disposable = item.doneSubjectObservable
        .debug("doneSubscriptions")
        .subscribe(
            onNext: {
                done in self.validateDone(done: done, item: item)
        })

    doneSubscription.disposed(by: disposeBag)

All I've done is moved .disposed(by: disposeBag) out of the subscription chain.

Am I missing something, aren't these two approaches equivalent?

Upvotes: 0

Views: 466

Answers (1)

Sweeper
Sweeper

Reputation: 270850

No, they are not equivalent.

In the first case, you are storing the return value of this whole expression into doneSubscription, a variable of type Disposable:

item.doneSubjectObservable
    .debug("doneSubscriptions")
    .subscribe(
        onNext: {
            done in self.validateDone(done: done, item: item)
    }).disposed(by: disposeBag)

Since disposed(by:) does not return anything, this gives you an error. In the second case however, you actually assigned a Disposable to the variable doneSubscription - the return value of subscribe.

To fix your first case, simply remove the variable declaration.

Upvotes: 5

Related Questions