daily pastebin goal
94%
SHARE
TWEET

Untitled

a guest Nov 24th, 2017 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class ProfileDataSourceRx(private val profileApi: ProfileApi,
  2.                           private val database: AppDatabase): ProfileDataSource {
  3.  
  4.     private val mediator = MediatorLiveData<ProfileResponse>()
  5.     private val errorLiveData = MutableLiveData<String>()
  6.  
  7.     override fun fetchProfile(profileId: String): LiveData<ProfileResponse> {
  8.         fetchProfileFromNetwork(profileId)
  9.         val databaseSource = database.profileDao().findById(profileId)
  10.         mediator.addSource(databaseSource) {
  11.             mediator.postValue(ProfileResponse.Success(it ?: Profile()))
  12.         }
  13.         mediator.addSource(errorLiveData) {
  14.             mediator.postValue(ProfileResponse.Error(it ?: ""))
  15.         }
  16.         return mediator
  17.     }
  18.  
  19.     private fun fetchProfileFromNetwork(profileId: String) {
  20.         profileApi.getObservableUser(profileId)
  21.                 .observeOn(Schedulers.io())
  22.                 .subscribeOn(Schedulers.io())
  23.                 .subscribe(this::next, this::error)//these are called from background thread
  24.     }
  25.  
  26.     private fun next(profile: Profile) {
  27.         database.profileDao().insert(profile)
  28.     }
  29.  
  30.     private fun error(error: Throwable) {
  31.         errorLiveData.postValue(error.message ?: "network_error")
  32.     }
  33. }
RAW Paste Data
Top