-
Notifications
You must be signed in to change notification settings - Fork 212
ДЗ ReactiveCats #214
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
ДЗ ReactiveCats #214
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,11 +1,12 @@ | ||
| package otus.homework.reactivecats | ||
|
|
||
| import retrofit2.Call | ||
| import io.reactivex.Single | ||
| import retrofit2.http.GET | ||
|
|
||
| interface CatsService { | ||
|
|
||
| //@GET("random?animal_type=cat") | ||
| @GET("fact") | ||
| fun getCatFact(): Call<Fact> | ||
| fun getCatFact(): Single<Fact> | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,40 +5,111 @@ import androidx.lifecycle.LiveData | |
| import androidx.lifecycle.MutableLiveData | ||
| import androidx.lifecycle.ViewModel | ||
| import androidx.lifecycle.ViewModelProvider | ||
| import retrofit2.Call | ||
| import retrofit2.Callback | ||
| import retrofit2.Response | ||
| import io.reactivex.Single | ||
|
|
||
| import io.reactivex.android.schedulers.AndroidSchedulers | ||
| import io.reactivex.disposables.CompositeDisposable | ||
| import io.reactivex.schedulers.Schedulers | ||
| import java.util.concurrent.TimeUnit | ||
|
|
||
|
|
||
| class CatsViewModel( | ||
| catsService: CatsService, | ||
| localCatFactsGenerator: LocalCatFactsGenerator, | ||
| context: Context | ||
| private val catsService: CatsService, | ||
| private val localCatFactsGenerator: LocalCatFactsGenerator, | ||
| private val context: Context | ||
| ) : ViewModel() { | ||
|
|
||
| // private val _catsLiveData = MutableLiveData<Result>() | ||
| // val catsLiveData: LiveData<Result> = _catsLiveData | ||
|
|
||
| private val compositeDisposable = CompositeDisposable() | ||
| private val _catsLiveData = MutableLiveData<Result>() | ||
| val catsLiveData: LiveData<Result> = _catsLiveData | ||
|
|
||
|
|
||
| init { | ||
| catsService.getCatFact().enqueue(object : Callback<Fact> { | ||
| override fun onResponse(call: Call<Fact>, response: Response<Fact>) { | ||
| if (response.isSuccessful && response.body() != null) { | ||
| _catsLiveData.value = Success(response.body()!!) | ||
| } else { | ||
| _catsLiveData.value = Error( | ||
| response.errorBody()?.string() ?: context.getString( | ||
| R.string.default_error_text | ||
| ) | ||
|
|
||
| getFacts() | ||
|
|
||
| // catsService.getCatFact().enqueue(object : Callback<Fact> { | ||
| // override fun onResponse(call: Call<Fact>, response: Response<Fact>) { | ||
| // if (response.isSuccessful && response.body() != null) { | ||
| // _catsLiveData.value = Success(response.body()!!) | ||
| // } else { | ||
| // _catsLiveData.value = Error( | ||
| // response.errorBody()?.string() ?: context.getString( | ||
| // R.string.default_error_text | ||
| // ) | ||
| // ) | ||
| // } | ||
| // } | ||
| // | ||
| // override fun onFailure(call: Call<Fact>, t: Throwable) { | ||
| // _catsLiveData.value = ServerError | ||
| // } | ||
| // }) | ||
| } | ||
|
|
||
| fun getFacts() { | ||
| // Очищаем предыдущие подписки перед новым запросом | ||
| compositeDisposable.clear() | ||
|
|
||
| val disposable = io.reactivex.Observable.interval(0, 2, TimeUnit.SECONDS) | ||
| .flatMapSingle { _ -> | ||
| catsService.getCatFact() | ||
| .onErrorResumeNext { throwable: Throwable -> | ||
| if (throwable is java.io.IOException) { | ||
| localCatFactsGenerator.generateCatFact() | ||
| } else { | ||
| io.reactivex.Single.error(throwable) | ||
| } | ||
| } | ||
| } | ||
| .subscribeOn(Schedulers.io()) | ||
| .observeOn(AndroidSchedulers.mainThread()) | ||
| .subscribe( | ||
| { fact -> | ||
| _catsLiveData.value = Result.Success(Single.just(fact)) | ||
| }, | ||
| { error -> | ||
| _catsLiveData.value = Result.Error(error.message ?: "Error") | ||
| } | ||
| ) | ||
|
|
||
| compositeDisposable.add(disposable) | ||
| } | ||
|
|
||
| private fun handleError(throwable: Throwable) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Метод не используется и его можно удалить |
||
| when { | ||
| throwable is java.net.ConnectException || | ||
| throwable is java.net.SocketTimeoutException || | ||
| throwable is java.net.UnknownHostException -> { | ||
| // Ошибка сети - используем локальный генератор | ||
| try { | ||
| val localFact = localCatFactsGenerator.generateCatFact() | ||
| _catsLiveData.value = Result.Success(localFact) | ||
| } catch (e: Exception) { | ||
| _catsLiveData.value = Result.Error( | ||
| context.getString(R.string.default_error_text) | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| override fun onFailure(call: Call<Fact>, t: Throwable) { | ||
| _catsLiveData.value = ServerError | ||
| throwable is retrofit2.HttpException -> { | ||
| // HTTP ошибка | ||
| _catsLiveData.value = Result.Error( | ||
| throwable.message ?: context.getString(R.string.default_error_text) | ||
| ) | ||
| } | ||
| }) | ||
| else -> { | ||
| _catsLiveData.value = Result.ServerError | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fun getFacts() {} | ||
| override fun onCleared() { | ||
| super.onCleared() | ||
| compositeDisposable.clear() | ||
| } | ||
| } | ||
|
|
||
| class CatsViewModelFactory( | ||
|
|
@@ -52,7 +123,9 @@ class CatsViewModelFactory( | |
| CatsViewModel(catsRepository, localCatFactsGenerator, context) as T | ||
| } | ||
|
|
||
| sealed class Result | ||
| data class Success(val fact: Fact) : Result() | ||
| data class Error(val message: String) : Result() | ||
| object ServerError : Result() | ||
| sealed class Result { | ||
| data class Success(val fact: Single<Fact>) : Result() | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Хранится Single, а в MainActivity используется result.fact как Fact |
||
| data class Error(val message: String) : Result() | ||
| data class Loading(val isLoading: Boolean) : Result() // Добавляем состояние загрузки | ||
| object ServerError : Result() | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Здесь передается Single.just(fact)
Если исправить sealed, то тут будет Result.Success(fact)