Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yongjhih/55595ba9b1c54a8246770d7f19c7d975 to your computer and use it in GitHub Desktop.
Save yongjhih/55595ba9b1c54a8246770d7f19c7d975 to your computer and use it in GitHub Desktop.
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