Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: HomeWork-06 Rx migration complete #132

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
3 changes: 2 additions & 1 deletion 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'
}
7 changes: 4 additions & 3 deletions 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 retrofit2.Call
import io.reactivex.Single
import retrofit2.Response
import retrofit2.http.GET

interface CatsService {

@GET("random?animal_type=cat")
fun getCatFact(): Call<Fact>
}
fun getCatFact(): Single<Response<Fact>>
Copy link
Collaborator

Choose a reason for hiding this comment

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

Можно убрать Response, CallAdapter сам неуспешные ответы от сервера смапит в исключения и бросит их по цепочке

}
88 changes: 70 additions & 18 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,92 @@ 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.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import java.lang.RuntimeException
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()
private val defaultErrorText = context.getString(R.string.default_error_text)

init {
catsService.getCatFact().enqueue(object : Callback<Fact> {
override fun onResponse(call: Call<Fact>, response: Response<Fact>) {
catsService.getCatFact()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map { response ->
if (response.isSuccessful && response.body() != null) {
_catsLiveData.value = Success(response.body()!!)
Success(response.body()!!)
} else {
_catsLiveData.value = Error(
response.errorBody()?.string() ?: context.getString(
R.string.default_error_text
)
)
Error(response.errorBody()?.string() ?: defaultErrorText)
}
}
.addSubscribe(
{ _catsLiveData.value = it },
{ _catsLiveData.value = ServerError }
)
}

override fun onFailure(call: Call<Fact>, t: Throwable) {
_catsLiveData.value = ServerError
fun getFacts() {
Observable.interval(0, 2, TimeUnit.SECONDS)
.subscribeOn(Schedulers.computation())
.flatMapSingle { catsService.getCatFact() }
.map { response ->
if (response.isSuccessful && response.body() != null) {
response.body()!!
} else {
throw RuntimeException("Wrong response: ${response.errorBody()?.string()}")
}
}
})
.onErrorResumeNext(
localCatFactsGenerator.generateCatFactPeriodically().toObservable()
)
.observeOn(AndroidSchedulers.mainThread())
.addSubscribe(
{ _catsLiveData.value = Success(it) },
{ _catsLiveData.value = ServerError }
)
}

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

private fun <T> Observable<T>.addSubscribe(
onSuccess: (T) -> Unit,
onError: (Throwable) -> Unit
) {
compositeDisposable.add(
this.subscribe(
{ onSuccess.invoke(it) },
{ onError.invoke(it) }
)
)
}

private fun <T> Single<T>.addSubscribe(
onSuccess: (T) -> Unit,
onError: (Throwable) -> Unit
) {
compositeDisposable.add(
this.subscribe(
{ onSuccess.invoke(it) },
{ onError.invoke(it) }
)
)
}
}

class CatsViewModelFactory(
Expand All @@ -55,4 +107,4 @@ class CatsViewModelFactory(
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: 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,18 +2,20 @@ package otus.homework.reactivecats

import android.content.Context
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()
}

val service 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,19 +3,29 @@ 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
context: Context
) {

private val random = java.util.Random()
private val array = context.resources.getStringArray(R.array.local_cat_facts)

private val catFactFlowable by lazy {
Flowable.interval(0,2000, TimeUnit.MILLISECONDS)
.map { getRandomFact() }
.distinctUntilChanged()
}

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

/**
Expand All @@ -24,7 +34,14 @@ 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 catFactFlowable
}

private fun getRandomFact(): Fact {
return Fact(getRandomString())
}

private fun getRandomString(): String {
return array[random.nextInt(array.size - 1)]
}
}
}
3 changes: 2 additions & 1 deletion app/src/main/java/otus/homework/reactivecats/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,6 @@ class MainActivity : AppCompatActivity() {
ServerError -> Snackbar.make(view, "Network error", 1000).show()
}
}
catsViewModel.getFacts()
}
}
}