Search code examples
retrofitrx-javarx-java2android-roomrx-android

How to let RxJava Observables work even after activity is changed?


I am downloading 10 data objects using Retrofit and saving it to Room using RxJava in an Android application. I am doing this in a SplashActivity. After at least one object is downloaded I save it to Room and want to open HomeActivity and let the remaining 9 objects keep downloading. How can I do this?

Here is how I am doing so far

for (i in 1 until 10) {
            MyService().getObject(i, object : Callback<MyObject> {

                override fun onFailure(call: Call<MyObject>, t: Throwable) {
                    t.printStackTrace()
                }

                override fun onResponse(call: Call<MyObject>, response: Response<MyObject>) {
                    if (response.isSuccessful) {
                        val result = response.body()!!.data
                        Observable.fromCallable{
                            objectDao.insert(Object(result))}
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .doOnComplete {if (i == 1) startHomeActivity()}
                                .subscribe()
                    }
                }
            })
        }

Now my first problem is, App is crashing while opening HomeActivity. That I suppose coming from the fact that activity is no longer active but observable is working. I am not able to fix this.

My second problem is, using disposables. As far as I understood (with my little knowledge of RxJava), I have to dispose my observables in my onDestroy() method. But I don't want to dispose, as I want this service to keep running until it finishes downloading all objects.


Solution

  • Apparently, I just had to use Service and run my work within service so that whenever activity is closed, service is still running.