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 @@ -37,6 +37,7 @@ dependencies {
implementation 'androidx.core:core-ktx:1.12.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'
implementation 'com.google.code.gson:gson:2.10'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.11.0'
Expand Down
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,10 +1,11 @@
package otus.homework.reactivecats

import io.reactivex.Single
import retrofit2.Call
import retrofit2.http.GET

interface CatsService {

@GET("random?animal_type=cat")
fun getCatFact(): Call<Fact>
fun getCatFact(): Single<Fact>
}
57 changes: 37 additions & 20 deletions app/src/main/java/otus/homework/reactivecats/CatsViewModel.kt
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
package otus.homework.reactivecats

import android.annotation.SuppressLint
import android.content.Context
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

@SuppressLint("CheckResult")
class CatsViewModel(
catsService: CatsService,
localCatFactsGenerator: LocalCatFactsGenerator,
Expand All @@ -17,28 +22,39 @@ class CatsViewModel(

private val _catsLiveData = MutableLiveData<Result>()
val catsLiveData: LiveData<Result> = _catsLiveData
val disposable = 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(
catsService = catsService,
context = context,
localCatFactsGenerator = localCatFactsGenerator
)
}

override fun onFailure(call: Call<Fact>, t: Throwable) {
_catsLiveData.value = ServerError
fun getFacts(catsService: CatsService, localCatFactsGenerator: LocalCatFactsGenerator, context: Context) {
val dis = Flowable.interval(0, 2, TimeUnit.SECONDS)
.flatMapSingle {
catsService.getCatFact()
.onErrorResumeNext { localCatFactsGenerator.generateCatFact(context) }
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
_catsLiveData.value = Success(it)
},
{
_catsLiveData.value = Error(it.message.toString())
}
)
disposable.add(dis)
}

fun getFacts() {}
override fun onCleared() {
super.onCleared()
disposable.dispose()
}
}

class CatsViewModelFactory(
Expand All @@ -52,7 +68,8 @@ 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()
object ServerError : Result()
4 changes: 4 additions & 0 deletions app/src/main/java/otus/homework/reactivecats/DiContainer.kt
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
package otus.homework.reactivecats

import android.content.Context
import io.reactivex.internal.schedulers.RxThreadFactory
import io.reactivex.plugins.RxJavaPlugins
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

class DiContainer {

private val retrofit by lazy {
Retrofit.Builder()
.baseUrl("https://cat-fact.herokuapp.com/facts/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,67 @@ package otus.homework.reactivecats
import android.content.Context
import io.reactivex.Flowable
import io.reactivex.Single
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import kotlin.random.Random

class LocalCatFactsGenerator(
private val context: Context
) {
private var atomicFact: AtomicReference<Fact> = AtomicReference()
private val localCatFacts = context.resources.getStringArray(R.array.local_cat_facts)

/**
* Реализуйте функцию otus.homework.reactivecats.LocalCatFactsGenerator#generateCatFact так,
* чтобы она возвращала Fact со случайной строкой из массива строк R.array.local_cat_facts
* обернутую в подходящий стрим(Flowable/Single/Observable и т.п)
*/
fun generateCatFact(): Single<Fact> {
return Single.never()
fun generateCatFact(context: Context): Single<Fact> {
return Single.create { emitter ->
emitter.onSuccess(getRandomCatFact(context))
}
}

/**
* Реализуйте функцию otus.homework.reactivecats.LocalCatFactsGenerator#generateCatFactPeriodically так,
* чтобы она эмитила Fact со случайной строкой из массива строк R.array.local_cat_facts каждые 2000 миллисекунд.
* Если вновь заэмиченный Fact совпадает с предыдущим - пропускаем элемент.
*/
fun generateCatFactPeriodically(): Flowable<Fact> {
val success = Fact(context.resources.getStringArray(R.array.local_cat_facts)[Random.nextInt(5)])
return Flowable.empty()
fun generateCatFactPeriodically(context: Context): Flowable<Fact> =
Flowable
.interval(0, 2, TimeUnit.SECONDS)
.map {
getRandomCatFact(context)
}.distinctUntilChanged()


/**
* We don't have daley after emitting the same fact anymore
*/
fun generateCatFactPeriodicallySecondEdition(context: Context): Flowable<Fact> =
Flowable
.interval(0, 2, TimeUnit.SECONDS)
.map {
getRandomCatFactSecondEdition(context, atomicFact)
}

private fun getRandomCatFact(context: Context): Fact {
return Fact(localCatFacts[Random.nextInt(localCatFacts.size)])
}

private fun getRandomCatFactSecondEdition(
context: Context,
atomicFact: AtomicReference<Fact>
): Fact {
var newFact: Fact = getRandomCatFact(context)
if (atomicFact.get() == newFact) {
while (atomicFact.get() == newFact) {
newFact = getRandomCatFact(context)
}
atomicFact.set(newFact)
} else {
atomicFact.set(newFact)
}
return newFact
}
}