Skip to content
Open

done #158

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 @@ -46,4 +46,5 @@ dependencies {
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.7.0'
implementation "io.reactivex.rxjava2:rxjava:2.2.21"
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
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,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>
}
47 changes: 28 additions & 19 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,49 @@ import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.concurrent.TimeUnit

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

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

private val compositeDisposable = 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
}
})
private fun getFacts() {
compositeDisposable.add(
Observable.interval(2000, TimeUnit.MILLISECONDS).timeInterval()
.flatMap {
catsService.getCatFact().toObservable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.onErrorResumeNext(localCatFactsGenerator.generateCatFact().toObservable())
}
.subscribe { result ->
Copy link
Contributor

Choose a reason for hiding this comment

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

Я бы все равно добавил обработчик ошибок. Ведь они теоретически и в localCatFactsGenerator.generateCatFact().toObservable() может выпасть

_catsLiveData.value = Success(result)
}
)
}

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

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 @@ -2,20 +2,24 @@ package otus.homework.reactivecats

import android.content.Context
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.Single
import java.util.concurrent.TimeUnit
import kotlin.random.Random

class LocalCatFactsGenerator(
private val context: Context
) {

val array = 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()
return Single.just(array[Random.nextInt(array.size)]).map { Fact(it) }
}

/**
Expand All @@ -24,7 +28,9 @@ 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(2000, TimeUnit.MILLISECONDS)
.map { Fact(array[Random.nextInt(array.size)]) }
.distinctUntilChanged()
}
}