Search code examples
androidkotlinrx-javarx-java2

RxJava2 - Subscribing PublishSubject


 private val searchSubject =  PublishSubject.create<Boolean>()
private val compositeDisposable = CompositeDisposable()

fun textChange(){
    searSubject.onNext(true)
}

fun getSubject(){
    compositeDisposable += searchSubject
        .doOnNext {
            if (it) showLoading()
        }
        .switchMap { searchGithubReposObservable() }
        .subscribeWith(object : DisposableObserver<List<GithubRepo>>() {
            override fun onNext(t: List<GithubRepo>) {
                hideLoading()
                adapter.items = t
            }

            override fun onComplete() {
            }

            override fun onError(e: Throwable) {
                hideLoading()
            }
        })
}
  • searchGithubReposObservable is the fucntion that returns the Observable<List<GithubRepo>>

I searched the sample code in the github for studying RxJava. However, I can't understand the above code.

I know that to receive data from PublishSubject, I need to subscribe it.

In the above code, I thought that subscribeWith subscribes searchGithubReposObservable()'s return Observable , but I could get the data from PublishSubject when the textchange() is called.

Why is it possible?


Solution

  • The start of your RX chain you are listening to the publish subject.

    compositeDisposable += searchSubject
        .doOnNext {
            if (it) showLoading()
        }
    

    Each time you call method textChange() you push to searchSubject which fires the RX chain all over again trigging the switchmap.