Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
5 changes: 3 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ plugins {
}

android {
compileSdkVersion 30
compileSdkVersion 33
buildToolsVersion "30.0.3"

defaultConfig {
applicationId "otus.homework.reactivecats"
minSdkVersion 23
targetSdkVersion 30
targetSdkVersion 33
versionCode 1
versionName "1.0"

Expand Down Expand Up @@ -46,4 +46,5 @@ dependencies {
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation "io.reactivex.rxjava2:rxjava:2.2.21"
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
}
21 changes: 21 additions & 0 deletions app/src/main/java/otus/homework/reactivecats/CatFactsCallable.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package otus.homework.reactivecats

import java.util.concurrent.Callable
import kotlin.random.Random

class CatFactsCallable(
Copy link
Contributor

Choose a reason for hiding this comment

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

Первый раз вижу такую реализацию, а почему просто не вызвать Single/Oservable.fromCallable?

private val catFacts: Array<String>
) : Callable<Fact> {

private var previous: String? = null

override fun call(): Fact {
while (true) {
val fact = catFacts[Random.nextInt(5)]
return if (fact != previous) {
previous = fact
Fact(fact)
} else continue
}
}
}
4 changes: 2 additions & 2 deletions app/src/main/java/otus/homework/reactivecats/CatsService.kt
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package otus.homework.reactivecats

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

interface CatsService {

@GET("random?animal_type=cat")
fun getCatFact(): Call<Fact>
fun getCatFact(): Single<Fact>
}
52 changes: 28 additions & 24 deletions app/src/main/java/otus/homework/reactivecats/CatsViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,40 +5,44 @@ 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.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

class CatsViewModel(
catsService: CatsService,
localCatFactsGenerator: LocalCatFactsGenerator,
context: Context
val catsService: CatsService,
Copy link
Contributor

Choose a reason for hiding this comment

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

private

val localCatFactsGenerator: LocalCatFactsGenerator,
val context: Context
) : ViewModel() {

private val 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
)
)
}
}

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

fun getFacts() {
val disposable = catsService.getCatFact()
.subscribeOn(Schedulers.io())
.delay(2, TimeUnit.SECONDS)
.onErrorResumeNext(localCatFactsGenerator.generateCatFact())
.subscribe({
_catsLiveData.postValue(Success(it))
}, {
_catsLiveData.postValue(
Error(it.message ?: context.getString(R.string.default_error_text)))
})

compositeDisposable.add(disposable)
}

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

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/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.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,8 @@ class LocalCatFactsGenerator(
* обернутую в подходящий стрим(Flowable/Single/Observable и т.п)
*/
fun generateCatFact(): Single<Fact> {
return Single.never()
val catFacts = context.resources.getStringArray(R.array.local_cat_facts)
return Single.just(Fact(catFacts[Random.nextInt(5)]))
}

/**
Expand All @@ -24,7 +26,8 @@ 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 catFacts = context.resources.getStringArray(R.array.local_cat_facts)
return Flowable.fromCallable(CatFactsCallable(catFacts))
.repeatWhen { it.delay(2, TimeUnit.SECONDS) }
Copy link
Contributor

Choose a reason for hiding this comment

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

Проверку на дубликат давай решим через специализированный оператор

}
}
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
@@ -1,10 +1,9 @@
package otus.homework.reactivecats

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.snackbar.Snackbar

class MainActivity : AppCompatActivity() {
Expand Down