Skip to content
Open

done #211

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
1 change: 1 addition & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,5 @@ dependencies {
implementation libs.picasso
implementation libs.rxjava
implementation libs.rxandroid
implementation libs.adapter.rxjava2
}
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>
}
62 changes: 40 additions & 22 deletions app/src/main/java/otus/homework/reactivecats/CatsViewModel.kt
Original file line number Diff line number Diff line change
@@ -1,55 +1,73 @@
package otus.homework.reactivecats

import android.content.Context
import android.net.http.HttpException
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import okio.IOException
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.concurrent.TimeUnit

class CatsViewModel(

Choose a reason for hiding this comment

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

context больше не нужен, можно убрать его отсюда и из CatsViewModelFactory

catsService: CatsService,
localCatFactsGenerator: LocalCatFactsGenerator,
context: Context
private val catsService: CatsService,
private val localCatFactsGenerator: LocalCatFactsGenerator
) : ViewModel() {

private val _catsLiveData = MutableLiveData<Result>()
val catsLiveData: LiveData<Result> = _catsLiveData
private val сompositeDisposable = CompositeDisposable()

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

override fun onFailure(call: Call<Fact>, t: Throwable) {
_catsLiveData.value = ServerError
fun getFacts() {

val disposable = Observable.interval(0, 2000, TimeUnit.MILLISECONDS)
.flatMapSingle {

Choose a reason for hiding this comment

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

лучше добавить subscribeOn чтобы запросы шли в фоновом потоке

catsService.getCatFact().onErrorResumeNext { localCatFactsGenerator.generateCatFact() }
}
})
.subscribeOn(Schedulers.io())
.distinctUntilChanged()
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
_catsLiveData.value = Success(it)
}, {
when (it) {
is IOException -> {
_catsLiveData.value = ServerError
}
else -> {
_catsLiveData.value = Error(it.message.toString())
}
}
})
сompositeDisposable.add(disposable)
}

fun getFacts() {}
override fun onCleared() {
super.onCleared()
сompositeDisposable.dispose()
}
}

class CatsViewModelFactory(
private val catsRepository: CatsService,
private val localCatFactsGenerator: LocalCatFactsGenerator,
private val context: Context
private val localCatFactsGenerator: LocalCatFactsGenerator
) :
ViewModelProvider.NewInstanceFactory() {

override fun <T : ViewModel> create(modelClass: Class<T>): T =
CatsViewModel(catsRepository, localCatFactsGenerator, context) as T
CatsViewModel(catsRepository, localCatFactsGenerator) 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 @@ -11,6 +12,7 @@ class DiContainer {
//.baseUrl("https://cat-fact.herokuapp.com/facts/")
.baseUrl("https://catfact.ninja/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ package otus.homework.reactivecats
import android.content.Context
import io.reactivex.Flowable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import io.reactivex.subscribers.DisposableSubscriber
import java.util.concurrent.TimeUnit
import kotlin.random.Random

class LocalCatFactsGenerator(
Expand All @@ -15,7 +19,8 @@ class LocalCatFactsGenerator(
* обернутую в подходящий стрим(Flowable/Single/Observable и т.п)
*/
fun generateCatFact(): Single<Fact> {
return Single.never()
val success = context.resources.getStringArray(R.array.local_cat_facts)[Random.nextInt(5)]
return Single.just(Fact(success))
}

/**
Expand All @@ -24,7 +29,12 @@ class LocalCatFactsGenerator(
* Если вновь заэмиченный Fact совпадает с предыдущим - пропускаем элемент.
*/
fun generateCatFactPeriodically(): Flowable<Fact> {
val success = Fact(context.resources.getStringArray(R.array.local_cat_facts)[Random.nextInt(5)])
return Flowable.empty()
val factsArray = context.resources.getStringArray(R.array.local_cat_facts)
return Flowable.interval(0, 2000, TimeUnit.MILLISECONDS)
.map {
val randomFact = factsArray[Random.nextInt(factsArray.size)]
Fact(randomFact)
}
.distinctUntilChanged()
}
}
3 changes: 1 addition & 2 deletions app/src/main/java/otus/homework/reactivecats/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ class MainActivity : AppCompatActivity() {
private val catsViewModel by viewModels<CatsViewModel> {
CatsViewModelFactory(
diContainer.service,
diContainer.localCatFactsGenerator(applicationContext),
applicationContext
diContainer.localCatFactsGenerator(applicationContext)
)
}

Expand Down
1 change: 1 addition & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ rxandroid = "2.1.1"
rxjava = "2.2.21"

[libraries]
adapter-rxjava2 = { module = "com.squareup.retrofit2:adapter-rxjava2", version.ref = "retrofit" }
core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "core-ktx" }
appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" }
material = { group = "com.google.android.material", name = "material", version.ref = "material" }
Expand Down