Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,7 @@ dependencies {
implementation libs.picasso
implementation libs.rxjava
implementation libs.rxandroid
implementation libs.rx.android.adapter
implementation libs.retrofit
implementation libs.retrofit.converter.gson
}
3 changes: 2 additions & 1 deletion app/src/main/java/otus/homework/reactivecats/CatsService.kt
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>
}
66 changes: 42 additions & 24 deletions app/src/main/java/otus/homework/reactivecats/CatsViewModel.kt
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() {

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()
}

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) {

Choose a reason for hiding this comment

The 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(
Expand All @@ -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
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/java/otus/homework/reactivecats/DiContainer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package otus.homework.reactivecats

import android.content.Context
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

class DiContainer {
Expand All @@ -10,6 +11,7 @@ class DiContainer {
Retrofit.Builder()
//.baseUrl("https://cat-fact.herokuapp.com/facts/")
.baseUrl("https://catfact.ninja/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package otus.homework.reactivecats
import android.content.Context
import io.reactivex.Flowable
import io.reactivex.Single
import java.util.concurrent.TimeUnit
import kotlin.random.Random

class LocalCatFactsGenerator(
Expand All @@ -15,7 +16,10 @@ class LocalCatFactsGenerator(
* обернутую в подходящий стрим(Flowable/Single/Observable и т.п)
*/
fun generateCatFact(): Single<Fact> {
return Single.never()
val strings = context.resources.getStringArray(R.array.local_cat_facts)
return Single.fromCallable {
(Fact(strings.random()))
}
}

/**
Expand All @@ -25,6 +29,10 @@ class LocalCatFactsGenerator(
*/
fun generateCatFactPeriodically(): Flowable<Fact> {
val success = Fact(context.resources.getStringArray(R.array.local_cat_facts)[Random.nextInt(5)])
return Flowable.empty()
return Flowable.interval(0,2, TimeUnit.MILLISECONDS)
.map {
success
}
.distinctUntilChanged()
}
}
6 changes: 6 additions & 0 deletions app/src/main/java/otus/homework/reactivecats/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -30,4 +31,9 @@ class MainActivity : AppCompatActivity() {
}
}
}

override fun onDestroy() {
catsViewModel.onDestroy()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Когда вы поправите VM, onCleared() вызывается системой автоматически при уничтожении ViewModel, вызывать его вручную не нужно
Эту строку надо будет просто убрать

super.onDestroy()
}
}
2 changes: 2 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ picasso = "2.71828"
retrofit = "2.9.0"
rxandroid = "2.1.1"
rxjava = "2.2.21"
rx-adapter = "3.0.0"

[libraries]
core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "core-ktx" }
Expand All @@ -32,6 +33,7 @@ picasso = { module = "com.squareup.picasso:picasso", version.ref = "picasso" }
retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" }
retrofit-converter-gson = { group = "com.squareup.retrofit2", name = "converter-gson", version.ref = "retrofit" }
rxandroid = { module = "io.reactivex.rxjava2:rxandroid", version.ref = "rxandroid" }
rx-android-adapter = { module = "com.squareup.retrofit2:adapter-rxjava2", version.ref = "rx-adapter" }
rxjava = { module = "io.reactivex.rxjava2:rxjava", version.ref = "rxjava" }

[bundles]
Expand Down