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
17 changes: 15 additions & 2 deletions flowcats/src/main/java/otus/homework/flowcats/CatsRepository.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package otus.homework.flowcats

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onStart

class CatsRepository(
private val catsService: CatsService,
Expand All @@ -11,8 +13,19 @@ class CatsRepository(
fun listenForCatFacts() = flow {
while (true) {
val latestNews = catsService.getCatFact()
emit(latestNews)
if (latestNews.isSuccessful && latestNews.body() != null)
emit(Result.Success(latestNews.body()!!))
else emit(Result.Error(latestNews.message()))
delay(refreshIntervalMs)
}
}
}.onStart {
emit(Result.Loading)
}.catch { error ->
emit(
Result.Error(
error.message ?: error.localizedMessage
?: "Непредвиденная ошибка. Обратитесь к разработчикам"
)
)
}
}
5 changes: 3 additions & 2 deletions flowcats/src/main/java/otus/homework/flowcats/CatsService.kt
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package otus.homework.flowcats

import retrofit2.http.GET
import retrofit2.Response

interface CatsService {

@GET("random?animal_type=cat")
suspend fun getCatFact(): Fact
@GET("fact")
suspend fun getCatFact(): Response<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
13 changes: 9 additions & 4 deletions flowcats/src/main/java/otus/homework/flowcats/CatsViewModel.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
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.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
Expand All @@ -10,8 +15,8 @@ class CatsViewModel(
private val catsRepository: CatsRepository
) : ViewModel() {

private val _catsLiveData = MutableLiveData<Fact>()
val catsLiveData: LiveData<Fact> = _catsLiveData
private val _catsLiveData: MutableStateFlow<Result?> = MutableStateFlow(null)
val catsLiveData: StateFlow<Result?> = _catsLiveData.asStateFlow()

init {
viewModelScope.launch {
Expand All @@ -26,6 +31,6 @@ class CatsViewModel(

class CatsViewModelFactory(private val catsRepository: CatsRepository) :
ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T =
override fun <T : ViewModel> create(modelClass: Class<T>): T =
CatsViewModel(catsRepository) as T
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class DiContainer {

private val retrofit by lazy {
Retrofit.Builder()
.baseUrl("https://cat-fact.herokuapp.com/facts/")
.baseUrl("https://catfact.ninja/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
Expand Down
22 changes: 4 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,8 @@ 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,
@field:SerializedName("length")
val length: Int
)
27 changes: 24 additions & 3 deletions flowcats/src/main/java/otus/homework/flowcats/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,21 +1,42 @@
package otus.homework.flowcats

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ProgressBar
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

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

@OptIn(InternalCoroutinesApi::class)
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 {
catsViewModel.catsLiveData.collect {
view.findViewById<ProgressBar>(R.id.progressBar).isVisible = it is Result.Loading
when (it) {
is Result.Success -> {
view.populate(it.fact)
}

is Result.Error -> {
Toast.makeText(this@MainActivity, it.message, Toast.LENGTH_LONG).show()
}

else -> {}
}
}
}
}
}
7 changes: 7 additions & 0 deletions flowcats/src/main/java/otus/homework/flowcats/Result.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package otus.homework.flowcats

sealed class Result {
data class Error(val message: String) : Result()
data class Success(val fact: Fact) : Result()
object Loading : Result()
}
11 changes: 11 additions & 0 deletions flowcats/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,15 @@
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminateTint="@color/purple_500"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</otus.homework.flowcats.CatsView>
47 changes: 40 additions & 7 deletions operators/src/main/java/otus/homework/flow/SampleInteractor.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
package otus.homework.flow

import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.zip

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

/**
Expand All @@ -28,8 +42,15 @@ class SampleInteractor(
* Если входное число делится на 15 - эмитим само число и после него эмитим строку FizzBuzz
* Если число не делится на 3,5,15 - эмитим само число
*/
fun task2(): Flow<String> {
return flowOf()
fun task2(): Flow<String> = flow {
sampleRepository.produceNumbers().collect { number ->
emit("$number")
when {
number % 15 == 0 -> emit("FizzBuzz")
number % 5 == 0 -> emit("Buzz")
number % 3 == 0 -> emit("Fizz")
}
}
}

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

/**
Expand All @@ -47,7 +73,14 @@ class SampleInteractor(
* Если тип эксепшена != IllegalArgumentException, пробросьте его дальше
* При любом исходе, будь то выброс исключения или успешная отработка функции вызовите метод dotsRepository.completed()
*/
fun task4(): Flow<Int> {
return flowOf()
fun task4(): Flow<Int> = flow {
sampleRepository.produceNumbers().collect { number ->
emit(number)
}
}.onCompletion {
sampleRepository.completed()
}.catch { error ->
if (error is IllegalArgumentException) emit(-1)
else throw error
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
package otus.homework.flow

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf

interface SampleRepository {

fun produceNumbers(): Flow<Int>
fun produceNumbers(): Flow<Int> = flowOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

fun produceColors(): Flow<String>
fun produceColors(): Flow<String> =
flowOf("Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Black", "White", "Gray")

fun produceForms(): Flow<String>
fun produceForms(): Flow<String> =
flowOf("Triangle", "Circle", "Square", "Rectangle", "Oval", "Rhombus")

fun completed()
}