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

home work RxJava, and fix comment #171

Open
wants to merge 2 commits 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
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.3.0'
}
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>
}
61 changes: 33 additions & 28 deletions app/src/main/java/otus/homework/reactivecats/CatsViewModel.kt
Original file line number Diff line number Diff line change
@@ -1,55 +1,60 @@
package otus.homework.reactivecats

import android.content.Context
import android.annotation.SuppressLint
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

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

private val subscriptionDisposables: 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
)
)
}
}
getFacts()
}

override fun onFailure(call: Call<Fact>, t: Throwable) {
_catsLiveData.value = ServerError
}
})
fun getFacts() {
val dispos = catsService.getCatFact()
.delay(2000, TimeUnit.MILLISECONDS)
.repeat()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ fact ->
_catsLiveData.value = Success(fact)
}, {
_catsLiveData.value =
Success(localCatFactsGenerator.generateCatFact().blockingGet())
}
)
subscriptionDisposables.add(dispos)
}

fun getFacts() {}
override fun onCleared() {
super.onCleared()
subscriptionDisposables.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
6 changes: 4 additions & 2 deletions app/src/main/java/otus/homework/reactivecats/DiContainer.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package otus.homework.reactivecats

import android.content.Context
import android.content.res.Resources
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

class DiContainer {
Expand All @@ -10,10 +11,11 @@ class DiContainer {
Retrofit.Builder()
.baseUrl("https://cat-fact.herokuapp.com/facts/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}

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

fun localCatFactsGenerator(context: Context) = LocalCatFactsGenerator(context)
fun localCatFactsGenerator(resources: Resources) = LocalCatFactsGenerator(resources)
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package otus.homework.reactivecats

import android.content.Context
import android.content.res.Resources
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 resources: Resources
) {

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

/**
Expand All @@ -24,7 +28,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()
var localFacts = ""
return Flowable.interval(2000, TimeUnit.MILLISECONDS).map {
localFacts = generateCatFactTest()
Fact(localFacts)
}
.distinctUntilChanged()
}

private fun generateCatFactTest() =
resources.getStringArray(R.array.local_cat_facts)[Random.nextInt(5)]
}
20 changes: 10 additions & 10 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 @@ -13,21 +12,22 @@ class MainActivity : AppCompatActivity() {
private val catsViewModel by viewModels<CatsViewModel> {
CatsViewModelFactory(
diContainer.service,
diContainer.localCatFactsGenerator(applicationContext),
applicationContext
diContainer.localCatFactsGenerator(applicationContext.resources)
)
}


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val view = layoutInflater.inflate(R.layout.activity_main, null) as CatsView
setContentView(view)
catsViewModel.catsLiveData.observe(this) { result ->
when (result) {
is Success -> view.populate(result.fact)
is Error -> Toast.makeText(this, result.message, Toast.LENGTH_LONG).show()
ServerError -> Snackbar.make(view, "Network error", 1000).show()
catsViewModel.catsLiveData
.observe(this) { result ->
when (result) {
is Success -> view.populate(result.fact)
is Error -> Toast.makeText(this, result.message, Toast.LENGTH_LONG).show()
ServerError -> Snackbar.make(view, "Network error", 1000).show()
}
}
}
}
}