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
7 changes: 5 additions & 2 deletions flowcats/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ plugins {
}

android {
compileSdkVersion 30
compileSdkVersion 34
buildToolsVersion "30.0.3"

namespace = "otus.homework.flowcats"

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

Expand Down Expand Up @@ -46,6 +46,9 @@ dependencies {
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3'
implementation 'androidx.activity:activity-ktx:1.2.3'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.3'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'

implementation 'androidx.lifecycle:lifecycle-viewmodel-android:2.8.6'
}
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
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)
}
28 changes: 18 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,39 @@
package otus.homework.flowcats

import androidx.lifecycle.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
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 _catsData = MutableStateFlow<Result>(Result.Empty)
val catsData: StateFlow<Result> = _catsData.asStateFlow()

init {
fun init() {
viewModelScope.launch {
withContext(Dispatchers.IO) {
catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
try {
catsRepository.listenForCatFacts().collect { fact ->
_catsData.value = Result.Success(fact)
}
} catch (e: Exception) {
_catsData.value = Result.Error("Error: " + e.message)
}
}
}
}

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
}

sealed class Result() {
data class Error(val message: String) : Result()
data class Success<T>(val result: T) : Result()
object Empty : Result()
}
34 changes: 32 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,12 @@ package otus.homework.flowcats

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

class MainActivity : AppCompatActivity() {

Expand All @@ -14,8 +19,33 @@ class MainActivity : AppCompatActivity() {
val view = layoutInflater.inflate(R.layout.activity_main, null) as CatsView
setContentView(view)

catsViewModel.catsLiveData.observe(this){
view.populate(it)
catsViewModel.init()

lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
catsViewModel.catsData.collect { result ->
when (result) {
is Result.Success<*> -> {
val fact = result.result as Fact
view.populate(fact)
}
is Result.Error -> {
Toast.makeText(
this@MainActivity,
result.message,
Toast.LENGTH_LONG
).show()
}
Result.Empty -> {
Toast.makeText(
this@MainActivity,
"Empty Result",
Toast.LENGTH_LONG
).show()
}
}
}
}
}
}
}
34 changes: 30 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 } // Умножаем на 5
.filter { it > 20 } // Фильтруем числа > 20
.filter { it % 2 != 0 } // Убираем четные числа
.map { "$it won" } // Добавляем постфикс
.take(3) // Берем первые 3 элемента
}

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

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

/**
Expand All @@ -48,6 +64,16 @@ 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()
}
}
}