Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pavel Iokhin Flow fxed #106

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
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
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package otus.homework.flowcats

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn

class CatsRepository(
private val catsService: CatsService,
Expand All @@ -14,5 +16,5 @@ class CatsRepository(
emit(latestNews)
delay(refreshIntervalMs)
}
}
}.flowOn(Dispatchers.IO)
}
11 changes: 11 additions & 0 deletions flowcats/src/main/java/otus/homework/flowcats/CatsView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package otus.homework.flowcats

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

Expand All @@ -14,9 +16,18 @@ class CatsView @JvmOverloads constructor(
override fun populate(fact: Fact) {
findViewById<TextView>(R.id.fact_textView).text = fact.text
}

override fun setLoadingVisible(visible: Boolean) {
findViewById<ProgressBar>(R.id.loading).visibility = if (visible) {
View.VISIBLE
} else {
View.GONE
}
}
}

interface ICatsView {

fun populate(fact: Fact)
fun setLoadingVisible(visible: Boolean)
}
26 changes: 10 additions & 16 deletions flowcats/src/main/java/otus/homework/flowcats/CatsViewModel.kt
Original file line number Diff line number Diff line change
@@ -1,27 +1,21 @@
package otus.homework.flowcats

import androidx.lifecycle.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.flow.*

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

private val _catsLiveData = MutableLiveData<Fact>()
val catsLiveData: LiveData<Fact> = _catsLiveData

init {
viewModelScope.launch {
withContext(Dispatchers.IO) {
catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
}
}
val catsState = catsRepository.listenForCatFacts()
.map { Result.Success(it) }
.catch<Result<Fact>> {
emit(Result.Error(it))
}
}
.stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5000),
Result.Loading
)
}

class CatsViewModelFactory(private val catsRepository: CatsRepository) :
Expand Down
21 changes: 19 additions & 2 deletions flowcats/src/main/java/otus/homework/flowcats/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ package otus.homework.flowcats

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

class MainActivity : AppCompatActivity() {

Expand All @@ -14,8 +18,21 @@ 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.catsState.collect {
when (it) {
is Result.Success -> {
view.setLoadingVisible(false)
view.populate(it.data)
}
is Result.Error -> Toast.makeText(
this@MainActivity,
it.exception.message,
Toast.LENGTH_SHORT
).show()
is Result.Loading -> view.setLoadingVisible(true)
}
}
}
}
}
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<out T : Any> {
data class Success<out T : Any>(val data: T) : Result<T>()
data class Error(val exception: Throwable) : Result<Nothing>()
object Loading : Result<Nothing>()
}
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/loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
/>

</otus.homework.flowcats.CatsView>
32 changes: 28 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,11 @@ class SampleInteractor(
* 6) возвращает результат
*/
fun task1(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers()
.map { it * 5 }
.filter { it > 20 && it % 2 == 1 }
.take(3)
.map { "$it won" }
}

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

/**
Expand All @@ -38,7 +52,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 +65,13 @@ class SampleInteractor(
* При любом исходе, будь то выброс исключения или успешная отработка функции вызовите метод dotsRepository.completed()
*/
fun task4(): Flow<Int> {
return flowOf()
return sampleRepository.produceNumbers()
.catch {
when (it) {
is java.lang.IllegalArgumentException -> emit(-1)
else -> throw it
}
}
.onCompletion { sampleRepository.completed() }
}
}