Search code examples
androidkotlinrx-java2android-paging

Disposing Observable Inside Android Paging Library Data Source


I want to observe my network call changes inside my PageKeyedDataSource and Dispose of the RxJava subscription after user quitting a Fragment which leads to Data Source destruction.

class ProjectDataSource : PageKeyedDataSource<Int, ProjectPresenter>(), KoinComponent {
    ...

    override fun loadInitial(
        params: LoadInitialParams<Int>,
        callback: LoadInitialCallback<Int, ProjectPresenter>
    ) {
        val subscription = mProjectRepository.getProjects(DEFAULT_TAKE, 0)
            .subscribe(
                { projectPresenters ->
                    ...
                },
                { throwable ->
                    ...
                }
            )
          //Where to dispose `subscription`
    }

    ...
}

I have RxJava subscription in both my Repository and DataSource that both perform different operations on data. A Repository converts a remote model to a presenter model and ...

I'm not really sure it's a good idea to observe data inside DataSource.


Solution

  • I cannot provide any substantial proof my way is "right way" but here is what I think and typically follow in implementation:

    1. Unless some really edge case, I do not handle disposing under repository or data source
    2. If my repository is using Rx, I'm simply exposing all my Rx entities (Completable's, Single's etc) to consumers (typically view models), they subscribe and they manage disposing (in many cases by clearing them in onCleared)
    3. If my paging data source is using Rx (which by the way can cause unwanted UI effects during invalidation, it is better to run blocking ops in data source loadInitial and methods alike), I'm routing CompositeDisposable instance from view model through data source factory.