-
Notifications
You must be signed in to change notification settings - Fork 212
HomeWork - Добавлен RxJava2 #216
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?
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 io.reactivex.Single | ||
| import retrofit2.Call | ||
| 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 |
|---|---|---|
| @@ -1,44 +1,62 @@ | ||
| package otus.homework.reactivecats | ||
|
|
||
| import android.content.Context | ||
| import android.content.res.Resources | ||
| 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.Flowable | ||
| 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 resource: Resources | ||
| ) : ViewModel() { | ||
|
|
||
| private val disposable: 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 | ||
| ) | ||
| ) | ||
| fun getFacts() { | ||
| disposable.add( | ||
| Flowable.interval(0,2000, TimeUnit.MILLISECONDS) | ||
| .subscribeOn(Schedulers.io()) | ||
| .flatMapSingle { | ||
| catsService | ||
| .getCatFact() | ||
| .subscribeOn(Schedulers.io()) | ||
| .onErrorResumeNext { | ||
| localCatFactsGenerator.generateCatFact() | ||
| } | ||
| } | ||
| } | ||
| .observeOn(AndroidSchedulers.mainThread()) | ||
| .subscribe(::success, ::error) | ||
| ) | ||
| } | ||
|
|
||
| fun onDestroy() { | ||
| disposable.clear() | ||
| } | ||
|
|
||
| private fun success(fact: Fact) { | ||
| _catsLiveData.value = Success(fact) | ||
| } | ||
|
|
||
| override fun onFailure(call: Call<Fact>, t: Throwable) { | ||
| _catsLiveData.value = ServerError | ||
| } | ||
| }) | ||
| private fun error(error: 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. Метод создает объект Error, но не устанавливает его в _catsLiveData. Наши подписки при ошибке на UI не получает уведомление. _catsLiveData.value = Error... |
||
| Error( | ||
| error.message ?: resource.getString( | ||
| R.string.default_error_text | ||
| ) | ||
| ) | ||
| } | ||
|
|
||
| fun getFacts() {} | ||
|
|
||
| } | ||
|
|
||
| class CatsViewModelFactory( | ||
|
|
@@ -49,7 +67,7 @@ class CatsViewModelFactory( | |
| ViewModelProvider.NewInstanceFactory() { | ||
|
|
||
| override fun <T : ViewModel> create(modelClass: Class<T>): T = | ||
| CatsViewModel(catsRepository, localCatFactsGenerator, context) as T | ||
| CatsViewModel(catsRepository, localCatFactsGenerator, context.resources) as T | ||
| } | ||
|
|
||
| sealed class Result | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -22,6 +22,7 @@ class MainActivity : AppCompatActivity() { | |
| super.onCreate(savedInstanceState) | ||
| val view = layoutInflater.inflate(R.layout.activity_main, null) as CatsView | ||
| setContentView(view) | ||
| catsViewModel.getFacts() | ||
| catsViewModel.catsLiveData.observe(this) { result -> | ||
| when (result) { | ||
| is Success -> view.populate(result.fact) | ||
|
|
@@ -30,4 +31,9 @@ class MainActivity : AppCompatActivity() { | |
| } | ||
| } | ||
| } | ||
|
|
||
| override fun onDestroy() { | ||
| catsViewModel.onDestroy() | ||
|
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. Когда вы поправите VM, onCleared() вызывается системой автоматически при уничтожении ViewModel, вызывать его вручную не нужно |
||
| super.onDestroy() | ||
| } | ||
| } | ||
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.
onDestroy() метод Activity/Fragment. ViewModel должен переопределять onCleared(), который вызывается системой при уничтожении VM. onDestroy() в VM не вызывается автоматически, поэтому подписки не отписываются, что приводит к утечкам памяти
override fun onCleared() {
super.onCleared()
disposable.clear()
}