Skip to content
Open

HW_3 #230

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
6 changes: 4 additions & 2 deletions flowcats/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@ plugins {
}

android {
compileSdkVersion 30
compileSdkVersion 34
buildToolsVersion "30.0.3"

namespace = "otus.homework.flowcats"

defaultConfig {
applicationId "otus.homework.flowcats"
minSdkVersion 23
targetSdkVersion 30
compileSdkVersion 34
targetSdkVersion 34
versionCode 1
versionName "1.0"

Expand Down Expand Up @@ -48,4 +49,5 @@ dependencies {
implementation 'androidx.activity:activity-ktx:1.2.3'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.3'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0'
}
6 changes: 4 additions & 2 deletions flowcats/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Flow" >
<activity android:name=".MainActivity">
android:theme="@style/Theme.Flow">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@ class CatsRepository(

fun listenForCatFacts() = flow {
while (true) {
val latestNews = catsService.getCatFact()
emit(latestNews)
try {
val latestNews = catsService.getCatFact()
emit(Result.Success(latestNews))
} catch (e: Exception) {
emit(Result.Error(e.message))

Choose a reason for hiding this comment

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

при ошибке нет задержки до следующего запроса, потенциально можем закидать ненужными запросами сервер, лучше задержку вынести из try

}
delay(refreshIntervalMs)
}
}
Expand Down
5 changes: 4 additions & 1 deletion flowcats/src/main/java/otus/homework/flowcats/CatsService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import retrofit2.http.GET

interface CatsService {

@GET("random?animal_type=cat")
/*@GET("random?animal_type=cat")
suspend fun getCatFact(): Fact*/

@GET("fact")
suspend fun getCatFact(): Fact
}
16 changes: 13 additions & 3 deletions flowcats/src/main/java/otus/homework/flowcats/CatsView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package otus.homework.flowcats
import android.content.Context
import android.util.AttributeSet
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout

class CatsView @JvmOverloads constructor(
Expand All @@ -11,12 +12,21 @@ class CatsView @JvmOverloads constructor(
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr), ICatsView {

override fun populate(fact: Fact) {
findViewById<TextView>(R.id.fact_textView).text = fact.text
override fun populate(result: Result) {
when (result) {
is Result.Success<*> -> {
if (result.data is Fact) {
findViewById<TextView>(R.id.fact_textView).text = result.data.fact
}
}
is Result.Error -> {
Toast.makeText(context, result.msg, Toast.LENGTH_SHORT).show()
}
}
}
}

interface ICatsView {

fun populate(fact: Fact)
fun populate(result: Result)
}
39 changes: 29 additions & 10 deletions flowcats/src/main/java/otus/homework/flowcats/CatsViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,49 @@ package otus.homework.flowcats

import androidx.lifecycle.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class CatsViewModel(
private val catsRepository: CatsRepository
) : ViewModel() {

private val _catsLiveData = MutableLiveData<Fact>()
val catsLiveData: LiveData<Fact> = _catsLiveData
//private val _catsLiveData = MutableStateFlow(Fact("", false, "0", "", "", false, "", "", ""))
private val _catsLiveData = MutableStateFlow<Result>(value = Result.Success<Fact>(Fact("", 0)))
val catsFlowData: StateFlow<Result> = _catsLiveData.asStateFlow()

init {
viewModelScope.launch {
withContext(Dispatchers.IO) {
catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
catsRepository.listenForCatFacts()
.flowOn(Dispatchers.IO)
.catch { e ->
_catsLiveData.emit(Result.Error(e.message.toString()))
}
.collect {
_catsLiveData.emit(it)
}
}
}
}
}

class CatsViewModelFactory(private val catsRepository: CatsRepository) :
ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T =
CatsViewModel(catsRepository) as T
}
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(CatsViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return CatsViewModel(catsRepository) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}

sealed class Result {
data class Success<T>(val data: T) : Result()
data class Error(val msg: String?) : Result()

}
3 changes: 2 additions & 1 deletion flowcats/src/main/java/otus/homework/flowcats/DiContainer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ class DiContainer {

private val retrofit by lazy {
Retrofit.Builder()
.baseUrl("https://cat-fact.herokuapp.com/facts/")
//.baseUrl("https://cat-fact.herokuapp.com/facts/")
.baseUrl("https://catfact.ninja/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
Expand Down
8 changes: 6 additions & 2 deletions flowcats/src/main/java/otus/homework/flowcats/Fact.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package otus.homework.flowcats
import com.google.gson.annotations.SerializedName

data class Fact(
@field:SerializedName("createdAt")
/*@field:SerializedName("createdAt")
val createdAt: String,
@field:SerializedName("deleted")
val deleted: Boolean,
Expand All @@ -20,5 +20,9 @@ data class Fact(
@field:SerializedName("user")
val user: String,
@field:SerializedName("updatedAt")
val updatedAt: String
val updatedAt: String*/
@field:SerializedName("fact")
val fact: String,
@field:SerializedName("length")
val length: Int
)
15 changes: 13 additions & 2 deletions flowcats/src/main/java/otus/homework/flowcats/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,30 @@ package otus.homework.flowcats
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch


class MainActivity : AppCompatActivity() {

private val diContainer = DiContainer()
private val catsViewModel by viewModels<CatsViewModel> { CatsViewModelFactory(diContainer.repository) }


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){
view.populate(it)
lifecycleScope.launch {

Choose a reason for hiding this comment

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

тут лучше добавить repeatOnLifecycle(Lifecycle.State.STARTED), чтобы в STOPPED не продолжать работу

repeatOnLifecycle(Lifecycle.State.STARTED){
catsViewModel.catsFlowData.collectLatest {
view.populate(it)
}
}
}
}
}
50 changes: 46 additions & 4 deletions operators/src/main/java/otus/homework/flow/SampleInteractor.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package otus.homework.flow

import android.widget.Space
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*

Expand All @@ -18,7 +19,16 @@ class SampleInteractor(
* 6) возвращает результат
*/
fun task1(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers()
.map {
it.times(5)
}.filter {
it > 20
}.filter {
it % 2 != 0
}.map {
"$it won"
}.take(3)
}

/**
Expand All @@ -29,7 +39,27 @@ class SampleInteractor(
* Если число не делится на 3,5,15 - эмитим само число
*/
fun task2(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers()
.transform {
when {
it % 15 == 0 -> {
emit(it.toString())
emit("FizzBuzz")
}

it % 3 == 0 -> {
emit(it.toString())
emit("Fizz")
}

it % 5 == 0 -> {
emit(it.toString())
emit("Buzz")
}

else -> emit(it.toString())
}
}
}

/**
Expand All @@ -38,7 +68,10 @@ class SampleInteractor(
* Если айтемы в одно из флоу кончились то результирующий флоу также должен закончится
*/
fun task3(): Flow<Pair<String, String>> {
return flowOf()
return sampleRepository.produceColors()
.zip(sampleRepository.produceForms()) { color, form ->
Pair(color, form)
}
}

/**
Expand All @@ -48,6 +81,15 @@ class SampleInteractor(
* При любом исходе, будь то выброс исключения или успешная отработка функции вызовите метод dotsRepository.completed()
*/
fun task4(): Flow<Int> {
return flowOf()
return sampleRepository.produceNumbers()
.catch {
if (it is IllegalArgumentException) {
emit(-1)
} else {
throw it
}
}.onCompletion {
sampleRepository.completed()
}
}
}