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
13 changes: 9 additions & 4 deletions flowcats/src/main/java/otus/homework/flowcats/CatsRepository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,21 @@ package otus.homework.flowcats

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlin.coroutines.cancellation.CancellationException

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

fun listenForCatFacts() = flow {
fun listenForCatFacts() = flow<Result<Fact>> {
while (true) {
val latestNews = catsService.getCatFact()
emit(latestNews)
try {
val latestNews = catsService.getCatFact()
emit(Result.Success(latestNews))
} catch (e: Exception) {
if (e is CancellationException) throw e
emit(Result.Error(e))
}
delay(refreshIntervalMs)
}
}
Expand Down
20 changes: 19 additions & 1 deletion flowcats/src/main/java/otus/homework/flowcats/CatsView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,26 @@ class CatsView @JvmOverloads constructor(
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr), ICatsView {

private lateinit var textView: TextView

override fun onFinishInflate() {
super.onFinishInflate()
textView = findViewById(R.id.fact_textView)
}

override fun populate(fact: Fact) {
findViewById<TextView>(R.id.fact_textView).text = fact.text
textView.text = fact.text
textView.setTextColor(context.getColor(android.R.color.black))
}

fun showError(errorMessage: String) {
textView.text = "Error: $errorMessage"
textView.setTextColor(context.getColor(android.R.color.holo_red_dark))
}

fun showLoading() {
textView.text = "Loading..."
textView.setTextColor(context.getColor(android.R.color.darker_gray))
}
}

Expand Down
36 changes: 26 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,47 @@
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.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 _catsState = MutableStateFlow<Result<Fact>>(Result.Loading)
val catsState: StateFlow<Result<Fact>> = _catsState

init {
loadCatFacts()
}

private fun loadCatFacts() {
viewModelScope.launch {
withContext(Dispatchers.IO) {
catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
catsRepository.listenForCatFacts()
.flowOn(Dispatchers.IO)
.collect { result ->
_catsState.value = result
}
}
}
}
}

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 {
return CatsViewModel(catsRepository) as T
}
}

sealed class Result<out T> {
data class Success<T>(val data: T) : Result<T>()
data class Error(val exception: Throwable) : Result<Nothing>()

object Loading : Result<Nothing>()
}
26 changes: 21 additions & 5 deletions flowcats/src/main/java/otus/homework/flowcats/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,21 +1,37 @@
package otus.homework.flowcats

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.collect

class MainActivity : AppCompatActivity() {

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

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 {
catsViewModel.catsState.collect { result ->
when (result) {
is Result.Success -> view.populate(result.data)
is Result.Error -> {
view.showError(result.exception.message ?: "Unknown error")
}

Result.Loading -> {
view.showLoading()
}
}
}
}
}
}
9 changes: 6 additions & 3 deletions flowcats/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<otus.homework.flowcats.CatsView xmlns:android="http://schemas.android.com/apk/res/android"
<otus.homework.flowcats.CatsView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rootView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

<TextView
android:id="@+id/fact_textView"
android:layout_width="wrap_content"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:text="Loading..."
android:textColor="@android:color/black"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
Expand Down
38 changes: 34 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,15 @@ class SampleInteractor(
* 6) возвращает результат
*/
fun task1(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers()
.map {
it * 5
}.filter { it > 20 }
.filter { it % 2 != 0 }
.take(3)
.map {
"$it won"
}
}

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

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

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

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