0

I am using Room and RxJava2 in Android application. I have a scenario inwhich I want to same function to run synchronously at some point and to run asynchronously on other place. Below is the function:

@Query("SELECT * from saved_survey WHERE enumeratorId = :enumeratorId and isDeleted=:isDeleted ORDER BY savedSurveyTime  DESC")
    fun getSavedSurveyList(enumeratorId: String, isDeleted: Boolean): Flowable<List<SavedSurvey>>

I want to run this function synchronously when called from IntentService and run asynchronously when called from UI thread. I am calling this function as:

savedSurveyViewModel.getSavedSurveyList(enumeratorId, false)
.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe()

I dont want to make multiple functions in repository or viewmodel. Any efficient approach will be appreciated.

Thanks

Mustansar Saeed
  • 2,730
  • 2
  • 22
  • 46

1 Answers1

0

I have found a solution. Same function can be used for synchronous and asynchronous. RxJava2 provides both of these behaviours.

Asynchronous

savedSurveyViewModel.getSavedSurveyList(enumeratorId, false)
.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe()

Synchronous

savedSurveyViewModel.getSavedSurveyList(enumeratorId, false).blockingSubscribe()

or

savedSurveyViewModel.getSavedSurveyList(enumeratorId, false).blockingSingle()

Thanks.

Mustansar Saeed
  • 2,730
  • 2
  • 22
  • 46