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
33 changes: 25 additions & 8 deletions flowcats/src/main/java/otus/homework/flowcats/CatsView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,38 @@ package otus.homework.flowcats

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout

class CatsView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr), ICatsView {
) : FrameLayout(context, attrs, defStyleAttr) {

override fun populate(fact: Fact) {
findViewById<TextView>(R.id.fact_textView).text = fact.text
}
}
private val factTextView: TextView by lazy { findViewById(R.id.fact_textView) }
private val progressBar: View by lazy { findViewById(R.id.progressBar) }

fun render(result: Result) {
when (result) {

interface ICatsView {
is Result.Loading -> {
progressBar.visibility = VISIBLE
factTextView.visibility = GONE
}

fun populate(fact: Fact)
is Result.Success -> {
progressBar.visibility = GONE
factTextView.visibility = VISIBLE
factTextView.text = result.fact.text
}

is Result.Error -> {
progressBar.visibility = GONE
factTextView.visibility = VISIBLE
factTextView.text = context.getString(R.string.error_text)
}
}
}
}
22 changes: 13 additions & 9 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 android.util.Log
import androidx.lifecycle.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
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 _catsStateFlowData = MutableStateFlow<Result>(Result.Loading)
val catsStateFlowData: StateFlow<Result> = _catsStateFlowData

init {
viewModelScope.launch {
withContext(Dispatchers.IO) {
catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
}
catsRepository.listenForCatFacts().catch { e ->
_catsStateFlowData.value = Result.Error(e)
Log.e("ApiError", e.toString())
}
.collect {
_catsStateFlowData.value = Result.Success(fact = it)
}
}
}
}

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
}
9 changes: 7 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,6 +3,9 @@ package otus.homework.flowcats
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.collect

class MainActivity : AppCompatActivity() {

Expand All @@ -14,8 +17,10 @@ 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 {
catsViewModel.catsStateFlowData.collect {result ->
view.render(result)
}
}
}
}
9 changes: 9 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,9 @@
package otus.homework.flowcats

sealed class Result {
data class Success(val fact: Fact) : Result()

data class Error(val e: Throwable) : Result()

object Loading : Result()
}
14 changes: 10 additions & 4 deletions flowcats/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,15 @@
android:layout_height="wrap_content"
android:textColor="@color/black"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
android:visibility="gone"
android:layout_gravity="center"
/>

<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone"/>

</otus.homework.flowcats.CatsView>
1 change: 1 addition & 0 deletions flowcats/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
<resources>
<string name="app_name">Flow cats</string>
<string name="error_text">Произошла ошибка, попробуйете позже</string>
</resources>
37 changes: 33 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,7 @@ class SampleInteractor(
* 6) возвращает результат
*/
fun task1(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers().map { it*5 }.filter { it>20 }.filter { it%2!=0 }.map { "$it won" }.take(3)
}

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

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

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