Created
May 29, 2020 02:35
-
-
Save yongjhih/55595ba9b1c54a8246770d7f19c7d975 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DataSourceLifecycleSingleTransformer<T>( | |
private val lifecycle: MutableLiveData<DataSourceLifecycle> | |
) : SingleTransformer<T, T> { | |
override fun apply(upstream: Single<T>): SingleSource<T> { | |
return upstream | |
.doOnSubscribe { | |
lifecycle.postValue(Loading) | |
} | |
.doOnSuccess { | |
lifecycle.postValue(Loaded) | |
} | |
.doOnError { e -> | |
lifecycle.postValue(Error(e)) | |
} | |
} | |
} | |
class ResponseDataSourceLifecycleSingleTransformer<T>( | |
private val lifecycle: MutableLiveData<DataSourceLifecycle> | |
) : SingleTransformer<Response<T>, Response<T>> { | |
override fun apply(upstream: Single<Response<T>>): SingleSource<Response<T>> { | |
return upstream | |
.doOnSubscribe { | |
lifecycle.postValue(Loading) | |
} | |
.doOnSuccess { response -> | |
if (response.isSuccessful) { | |
lifecycle.postValue(Loaded) | |
} else { | |
lifecycle.postValue(Error(IllegalStateException(response.errorBody()?.string()))) | |
} | |
} | |
.doOnError { e -> | |
lifecycle.postValue(Error(e)) | |
} | |
} | |
} | |
fun <T> Single<T>.lifecycle( | |
lifecycle: MutableLiveData<DataSourceLifecycle> | |
): Single<T> { | |
return compose(DataSourceLifecycleSingleTransformer(lifecycle)) | |
} | |
fun <T> Single<Response<T>>.lifecycleResponse( | |
lifecycle: MutableLiveData<DataSourceLifecycle> | |
): Single<Response<T>> { | |
return compose(ResponseDataSourceLifecycleSingleTransformer(lifecycle)) | |
} | |
fun <T> Call<T>.single(): Single<Response<T>> { | |
return Single.create<Response<T>> { | |
enqueue( | |
onResponse = { _, response -> it.onSuccess(response) }, | |
onFailure = { _, e -> it.onError(e) } | |
) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment