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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@

*Создать sealed класс `Result`. Унаследовать от него классы `Success<T>`, `Error`. Использовать эти классы как стейт необходимый для рендеринга/отображени ошибки

### Реализовать функции с использование flow операторов
### Реализовать функции с использованием flow операторов

1. В классе `SampleInteractor` реализуйте функции `task1`-`task4` в соответствии с условиями. Для проверки функций используйте тесты в `SampleInteractorTest`
7 changes: 4 additions & 3 deletions flowcats/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ plugins {
}

android {
compileSdkVersion 30
compileSdkVersion 36
buildToolsVersion "30.0.3"

namespace = "otus.homework.flowcats"

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

Expand Down Expand Up @@ -46,6 +46,7 @@ dependencies {
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3'
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.9.4'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.3'
}
6 changes: 3 additions & 3 deletions flowcats/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="otus.homework.flowcats">
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

<uses-permission android:name="android.permission.INTERNET" />
<application
Expand All @@ -10,7 +9,8 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Flow" >
<activity android:name=".MainActivity">
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

Expand Down
13 changes: 11 additions & 2 deletions flowcats/src/main/java/otus/homework/flowcats/CatsRepository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,24 @@ package otus.homework.flowcats
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow

sealed class Result {
data class Success<T>(val data: T) : Result()
data class Error(val throwable: Throwable) : Result()
}

class CatsRepository(
private val catsService: CatsService,
private val refreshIntervalMs: Long = 5000
) {

fun listenForCatFacts() = flow {
while (true) {
val latestNews = catsService.getCatFact()
emit(latestNews)
try {
val fact = catsService.getCatFact()
emit(Result.Success<Fact>(fact))
} catch (e: Exception) {
emit(Result.Error(e))
}
delay(refreshIntervalMs)
}
}
Expand Down
3 changes: 2 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,7 @@ import retrofit2.http.GET

interface CatsService {

@GET("random?animal_type=cat")
// @GET("random?animal_type=cat")
@GET("fact")
suspend fun getCatFact(): Fact
}
2 changes: 1 addition & 1 deletion flowcats/src/main/java/otus/homework/flowcats/CatsView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class CatsView @JvmOverloads constructor(
) : ConstraintLayout(context, attrs, defStyleAttr), ICatsView {

override fun populate(fact: Fact) {
findViewById<TextView>(R.id.fact_textView).text = fact.text
findViewById<TextView>(R.id.fact_textView).text = fact.fact
}
}

Expand Down
24 changes: 14 additions & 10 deletions flowcats/src/main/java/otus/homework/flowcats/CatsViewModel.kt
Original file line number Diff line number Diff line change
@@ -1,31 +1,35 @@
package otus.homework.flowcats

import androidx.lifecycle.*
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
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 _catsStateFlow = MutableStateFlow<Result?>(null)
val catsStateFlow: StateFlow<Result?> = _catsStateFlow.asStateFlow()

init {
viewModelScope.launch {
withContext(Dispatchers.IO) {
catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
}
catsRepository.listenForCatFacts()

Choose a reason for hiding this comment

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

ошибки при получении по сети лучше бы обработать в репозитории, зачем вьюмодели о них что-то знать? это не ее ответственность

Copy link
Author

Choose a reason for hiding this comment

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

Согласен, избавил ViewModel от несвойственной ему работы

.collect { result ->
_catsStateFlow.value = result
}
}
}
}
}

class CatsViewModelFactory(private val catsRepository: CatsRepository) :
ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T =
class CatsViewModelFactory(private val catsRepository: CatsRepository) : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T =
CatsViewModel(catsRepository) as T
}
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
20 changes: 2 additions & 18 deletions flowcats/src/main/java/otus/homework/flowcats/Fact.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,6 @@ package otus.homework.flowcats
import com.google.gson.annotations.SerializedName

data class Fact(
@field:SerializedName("createdAt")
val createdAt: String,
@field:SerializedName("deleted")
val deleted: Boolean,
@field:SerializedName("_id")
val id: String,
@field:SerializedName("text")
val text: String,
@field:SerializedName("source")
val source: String,
@field:SerializedName("used")
val used: Boolean,
@field:SerializedName("type")
val type: String,
@field:SerializedName("user")
val user: String,
@field:SerializedName("updatedAt")
val updatedAt: String
@field:SerializedName("fact")
val fact: String
)
22 changes: 19 additions & 3 deletions flowcats/src/main/java/otus/homework/flowcats/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
package otus.homework.flowcats

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

Expand All @@ -14,8 +19,19 @@ class MainActivity : AppCompatActivity() {
val view = layoutInflater.inflate(R.layout.activity_main, null) as CatsView
setContentView(view)

catsViewModel.catsLiveData.observe(this){
view.populate(it)
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
catsViewModel.catsStateFlow.collect { result ->
result?.let {
when (it) {
is Result.Success<*> -> view.populate(it.data as Fact)
is Result.Error -> {
Toast.makeText(this@MainActivity, it.throwable.message, Toast.LENGTH_SHORT).show()
}
}
}
}
}
}
}
}
3 changes: 2 additions & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
kotlin.code.style=official
org.gradle.configuration-cache=true
3 changes: 1 addition & 2 deletions operators/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="otus.homework.flow">
xmlns:android="http://schemas.android.com/apk/res/android">

<application
android:allowBackup="true"
Expand Down
36 changes: 32 additions & 4 deletions operators/src/main/java/otus/homework/flow/SampleInteractor.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ class SampleInteractor(
* 6) возвращает результат
*/
fun task1(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers()
.map { number -> number * 5 }
.filter { number -> number > 20 }
.filter { number -> number % 2 != 0 }
.map { number -> "$number won" }
.take(3)
}

/**
Expand All @@ -29,7 +34,16 @@ class SampleInteractor(
* Если число не делится на 3,5,15 - эмитим само число
*/
fun task2(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers()
.transform { number ->
emit(number.toString())

when {
number % 15 == 0 -> emit("FizzBuzz")
number % 3 == 0 -> emit("Fizz")
number % 5 == 0 -> emit("Buzz")
}
}
}

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

return flow1.zip(flow2) { color, form ->
Pair(color, form)
}
}

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