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
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 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'
}
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>
}
33 changes: 27 additions & 6 deletions app/src/main/java/otus/homework/reactivecats/CatsViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ 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,
Expand All @@ -17,9 +19,10 @@ class CatsViewModel(

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

Choose a reason for hiding this comment

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

нужно отписаться в onCleared, чтобы не утекало


init {
catsService.getCatFact().enqueue(object : Callback<Fact> {
/*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()!!)
Expand All @@ -35,10 +38,28 @@ class CatsViewModel(
override fun onFailure(call: Call<Fact>, t: Throwable) {
_catsLiveData.value = ServerError
}
})
})*/
getFacts(catsService, localCatFactsGenerator)

Choose a reason for hiding this comment

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

если сделать catsService и localCatFactsGenerator полями (добавить в конструктор private val), то не надо будет прокидывать их в функцию, плюс заодно context удалить, он теперь не нужен

}

fun getFacts() {}
fun getFacts(catsService: CatsService, localCatFactsGenerator: LocalCatFactsGenerator) {
val dis = Flowable.interval(2, TimeUnit.SECONDS)
.flatMapSingle {
catsService.getCatFact()
.onErrorResumeNext { localCatFactsGenerator.generateCatFact() }
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
_catsLiveData.value = Success(it)
},
{
_catsLiveData.value = Error(it.message.toString())
}
)
disposable.add(dis)
}
}

class CatsViewModelFactory(
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()
return Single.fromCallable {
val facts = context.resources.getStringArray(R.array.local_cat_facts)
Fact(facts[Random.nextInt(facts.size)])
}
}

/**
Expand All @@ -24,7 +28,11 @@ class LocalCatFactsGenerator(
* Если вновь заэмиченный Fact совпадает с предыдущим - пропускаем элемент.
*/
fun generateCatFactPeriodically(): Flowable<Fact> {
val success = Fact(context.resources.getStringArray(R.array.local_cat_facts)[Random.nextInt(5)])
return Flowable.empty()
return Flowable.interval(2, TimeUnit.SECONDS)
.map {
val facts = context.resources.getStringArray(R.array.local_cat_facts)
Fact(facts[Random.nextInt(facts.size)])
}
.distinctUntilChanged()
}
}