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

Rx Homework #52

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
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
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.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.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>
}
66 changes: 41 additions & 25 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,55 @@ 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.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

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

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

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

override fun onFailure(call: Call<Fact>, t: Throwable) {
_catsLiveData.value = ServerError
}
})
compositeDisposable.add(
catsService.getCatFact()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
_catsLiveData.value = Success(it)
}, {
_catsLiveData.value = Error(it.message ?: context.getString(R.string.default_error_text))
})
)
}

fun getFacts() {}
fun getFacts() {
compositeDisposable.add(
catsService.getCatFact()
.subscribeOn(Schedulers.io())
.onErrorResumeNext(localCatFactsGenerator.generateCatFact())
.delay(2000, TimeUnit.MILLISECONDS)

Choose a reason for hiding this comment

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

Тут есть проблема, что если перевести девайс в авиа режим то берется только один факт из локального списка и обновление прекращается, а должны продолжать обновляться каждые 2 секунды

Copy link
Author

Choose a reason for hiding this comment

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

Поправил

.repeat()
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
_catsLiveData.value = Success(it)
}, {
_catsLiveData.value = Error(it.message ?: context.getString(R.string.default_error_text))
})
)
}

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

class CatsViewModelFactory(
Expand All @@ -55,4 +70,5 @@ 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()

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

import android.content.Context
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.Single
import kotlin.random.Random
Expand All @@ -15,7 +16,9 @@ class LocalCatFactsGenerator(
* обернутую в подходящий стрим(Flowable/Single/Observable и т.п)
*/
fun generateCatFact(): Single<Fact> {
return Single.never()
return Single.just (
Fact(context.resources.getStringArray(R.array.local_cat_facts)[Random.nextInt(5)])
)
}

/**
Expand All @@ -25,6 +28,9 @@ class LocalCatFactsGenerator(
*/
fun generateCatFactPeriodically(): Flowable<Fact> {
val success = Fact(context.resources.getStringArray(R.array.local_cat_facts)[Random.nextInt(5)])
return Flowable.empty()
return Flowable.create<Fact?>( { emitter ->

Choose a reason for hiding this comment

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

тут получается мы создаем поток данных один раз берем факт о коте, засыпаем на две секунды и больше ничего не происходит, можно посмотреть в сторону Flowable.interval()

Copy link
Author

Choose a reason for hiding this comment

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

Поправил

emitter.onNext(success)
Thread.sleep(2000)
}, BackpressureStrategy.BUFFER).distinctUntilChanged()
}
}