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
6 changes: 3 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
buildToolsVersion "30.0.3"
compileSdk 34
buildToolsVersion '34.0.0'

namespace = "otus.homework.flowcats"

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

Expand Down
3 changes: 2 additions & 1 deletion flowcats/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,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
27 changes: 20 additions & 7 deletions flowcats/src/main/java/otus/homework/flowcats/CatsRepository.kt
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
package otus.homework.flowcats

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

interface Repository {
suspend fun listenForCatFacts() : Flow<LoadResult>
}

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

fun listenForCatFacts() = flow {
while (true) {
val latestNews = catsService.getCatFact()
emit(latestNews)
delay(refreshIntervalMs)
}
override suspend fun listenForCatFacts(): Flow<LoadResult> {
return flow {
while (true){
try {
val latestNews = catsService.getCatFact()
emit(LoadResult.Success(latestNews.text))
delay(refreshIntervalMs)
} catch (e: Exception) {
emit(LoadResult.Error(e.message ?: "error"))
}
}
}.flowOn(Dispatchers.IO)
}
}
53 changes: 46 additions & 7 deletions flowcats/src/main/java/otus/homework/flowcats/CatsView.kt
Original file line number Diff line number Diff line change
@@ -1,22 +1,61 @@
package otus.homework.flowcats

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import com.google.android.material.textview.MaterialTextView

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

override fun populate(fact: Fact) {
findViewById<TextView>(R.id.fact_textView).text = fact.text
override fun populate(text: String) {
setText(text)
}
override fun showPrimaryColor() {
setTextColor(Color.BLACK)
}

override fun showLoadingColor() {
setTextColor(Color.GREEN)
}

override fun showErrorColor() {
setTextColor(Color.RED)
}
}

interface ICatsView {
interface ICatsUiState {

fun populate(fact: Fact)
fun show(catsView: ICatsView)

data class Success(private val text: String) : ICatsUiState {
override fun show(catsView: ICatsView) {
catsView.populate(text)
catsView.showPrimaryColor()
}
}

data class Loading(private val text: String) : ICatsUiState {
override fun show(catsView: ICatsView) {
catsView.populate(text)
catsView.showLoadingColor()
}
}

data class Error(private val message: String) : ICatsUiState {
override fun show(catsView: ICatsView) {
catsView.populate(message)
catsView.showErrorColor()
}
}
}

interface ICatsView {
fun populate(text: String)
fun showPrimaryColor()
fun showLoadingColor()
fun showErrorColor()
}
25 changes: 15 additions & 10 deletions flowcats/src/main/java/otus/homework/flowcats/CatsViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,35 @@ package otus.homework.flowcats

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

class CatsViewModel(
private val catsRepository: CatsRepository
private val catsRepository: CatsRepository,
private val mapper: LoadResult.Mapper<ICatsUiState>
) : ViewModel() {

private val _catsLiveData = MutableLiveData<Fact>()
val catsLiveData: LiveData<Fact> = _catsLiveData
private val _catsFlow = MutableStateFlow<ICatsUiState>(ICatsUiState.Loading("Loading..."))
val catsFlow = _catsFlow.asStateFlow()

init {
viewModelScope.launch {
withContext(Dispatchers.IO) {
catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
}
catsRepository.listenForCatFacts().collect { loadResult ->
_catsFlow.emit(loadResult.map(mapper))
}
}
}
}

class CatsViewModelFactory(private val catsRepository: CatsRepository) :
class CatsViewModelFactory(private val catsRepository: CatsRepository,
private val mapper: LoadResult.Mapper<ICatsUiState>) :
ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T =
CatsViewModel(catsRepository) as T

override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass == CatsViewModel::class.java) return CatsViewModel(catsRepository, mapper) as T
throw IllegalArgumentException()
}
}
45 changes: 45 additions & 0 deletions flowcats/src/main/java/otus/homework/flowcats/LoadResult.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package otus.homework.flowcats

interface LoadResult {
fun <T : Any> map(mapper: Mapper<T>): T

interface Mapper<T : Any> {

fun mapSuccess(fact: String): T
fun mapLoading(message: String): T
fun mapError(message: String): T
}

data class Success(private val fact: String) : LoadResult {
override fun <T : Any> map(mapper: Mapper<T>): T {
return mapper.mapSuccess(fact)
}
}

data class Loading(private val message: String) : LoadResult {
override fun <T : Any> map(mapper: Mapper<T>): T {
return mapper.mapLoading(message)
}
}

data class Error(private val message: String) : LoadResult {
override fun <T : Any> map(mapper: Mapper<T>): T {
return mapper.mapError(message)
}
}
}

class ResultMapper() : LoadResult.Mapper<ICatsUiState> {

override fun mapSuccess(fact: String): ICatsUiState {
return ICatsUiState.Success(fact)
}

override fun mapLoading(message: String): ICatsUiState {
return ICatsUiState.Loading(message)
}

override fun mapError(message: String): ICatsUiState {
return ICatsUiState.Error(message)
}
}
19 changes: 15 additions & 4 deletions flowcats/src/main/java/otus/homework/flowcats/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,30 @@ package otus.homework.flowcats
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

private lateinit var catsView: CatsView

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

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val view = layoutInflater.inflate(R.layout.activity_main, null) as CatsView
val view = layoutInflater.inflate(R.layout.activity_main, null)
setContentView(view)

catsViewModel.catsLiveData.observe(this){
view.populate(it)
catsView = findViewById(R.id.fact_textView)

lifecycleScope.launch {
catsViewModel.catsFlow.collect { result ->
result.show(catsView)
}
}
}
}
6 changes: 3 additions & 3 deletions flowcats/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<otus.homework.flowcats.CatsView xmlns:android="http://schemas.android.com/apk/res/android"
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

<TextView
<otus.homework.flowcats.CatsView
android:id="@+id/fact_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Expand All @@ -18,4 +18,4 @@
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</otus.homework.flowcats.CatsView>
</androidx.constraintlayout.widget.ConstraintLayout>
31 changes: 27 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 { it * 5 }
.filter { it > 20 }
.filter { it % 2 != 0 }
.map { "$it won" }
.take(3)
}

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

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

}

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