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 @@ -46,5 +46,6 @@ dependencies {
implementation libs.gson
implementation libs.picasso
implementation libs.rxjava
implementation libs.retrofit.rxjava
implementation libs.rxandroid
}
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,11 +1,11 @@
package otus.homework.reactivecats

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

interface CatsService {

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

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.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable


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

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

private fun getFacts() {
disposable.add(
localCatFactsGenerator.generateCatFactPeriodically()
.flatMap(::handleFactRequest)
.distinctUntilChanged()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(::onFactSuccess, ::onFactError)
)
}

private fun handleFactRequest(localFact: Fact): Flowable<Fact> {
return catsService.getCatFact()
.onErrorResumeNext { Single.just(localFact) }
.toFlowable()
}

fun getFacts() {}
private fun onFactSuccess(fact: Fact) {
_catsLiveData.value = Success(fact)
}

private fun onFactError(throwable: Throwable) {
_catsLiveData.value = Error(throwable.message!!)
}


override fun onCleared() {
super.onCleared()
disposable.clear()
}
}

class CatsViewModelFactory(
private val catsRepository: CatsService,
private val localCatFactsGenerator: LocalCatFactsGenerator,
private val context: Context
) :
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
4 changes: 3 additions & 1 deletion 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,10 +12,11 @@ class DiContainer {
//.baseUrl("https://cat-fact.herokuapp.com/facts/")
.baseUrl("https://catfact.ninja/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}

val service by lazy { retrofit.create(CatsService::class.java) }
val service: CatsService by lazy { retrofit.create(CatsService::class.java) }

fun localCatFactsGenerator(context: Context) = LocalCatFactsGenerator(context)
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,32 @@ 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(
private val context: Context
) {

private val localFactsArray by lazy { context.resources.getStringArray(R.array.local_cat_facts) }
private val localFactsSize by lazy { localFactsArray.size }

/**
* Реализуйте функцию otus.homework.reactivecats.LocalCatFactsGenerator#generateCatFact так,
* чтобы она возвращала Fact со случайной строкой из массива строк 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()
private fun generateCatFact() = Single.fromCallable {
Fact(localFactsArray[Random.nextInt(localFactsSize)])
}

/**
* Реализуйте функцию otus.homework.reactivecats.LocalCatFactsGenerator#generateCatFactPeriodically так,
* Реализуйте функцию [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(): Flowable<Fact> =
Flowable.interval(2000, TimeUnit.MILLISECONDS)
.flatMap { generateCatFact().toFlowable() }
.distinctUntilChanged()
}
4 changes: 1 addition & 3 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 All @@ -14,7 +13,6 @@ class MainActivity : AppCompatActivity() {
CatsViewModelFactory(
diContainer.service,
diContainer.localCatFactsGenerator(applicationContext),
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 @@ -31,6 +31,7 @@ okhttp-logging-interceptor = { group = "com.squareup.okhttp3", name = "logging-i
picasso = { module = "com.squareup.picasso:picasso", version.ref = "picasso" }
retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" }
retrofit-converter-gson = { group = "com.squareup.retrofit2", name = "converter-gson", version.ref = "retrofit" }
retrofit-rxjava= { group = "com.squareup.retrofit2", name = "adapter-rxjava2", version.ref = "retrofit" }
rxandroid = { module = "io.reactivex.rxjava2:rxandroid", version.ref = "rxandroid" }
rxjava = { module = "io.reactivex.rxjava2:rxjava", version.ref = "rxjava" }

Expand Down