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

HW Flow | Nuradil #98

Open
wants to merge 2 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
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.4.32"
ext.kotlin_version = "1.6.0"
repositories {
google()
jcenter()
Expand Down
5 changes: 3 additions & 2 deletions flowcats/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ plugins {
}

android {
compileSdkVersion 30
compileSdkVersion 32
buildToolsVersion "30.0.3"

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

Expand Down Expand Up @@ -46,4 +46,5 @@ dependencies {
implementation 'androidx.activity:activity-ktx:1.2.3'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.3'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.5.1"
}
6 changes: 4 additions & 2 deletions flowcats/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Flow" >
<activity android:name=".MainActivity">
android:theme="@style/Theme.Flow">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

Expand Down
7 changes: 7 additions & 0 deletions flowcats/src/main/java/otus/homework/flowcats/CatsView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package otus.homework.flowcats
import android.content.Context
import android.util.AttributeSet
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout

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

override fun showToast(message: String) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
}

interface ICatsView {

fun populate(fact: Fact)

fun showToast(message: String)
}
32 changes: 26 additions & 6 deletions flowcats/src/main/java/otus/homework/flowcats/CatsViewModel.kt
Original file line number Diff line number Diff line change
@@ -1,23 +1,43 @@
package otus.homework.flowcats

import androidx.lifecycle.*
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.MutableStateFlow
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
sealed class Result {
class Success<T>(val data: T) : Result()
class Error(val throwable: Throwable) : Result()
}

private val _result = MutableStateFlow<Result?>(null)
val resultObservable = _result.asStateFlow()

init {
viewModelScope.launch {
withContext(Dispatchers.IO) {
try {
catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
withContext(Dispatchers.IO) {
_result.value = Result.Success(it)
}
}
} catch (throwable: Throwable) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Думаю здесь тоже нужно пробросить cancellationException дальше

Copy link
Author

@zhnuradil zhnuradil Feb 4, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Чтобы не ломать механизм отмены корутин? На любых иерархии корутин бросать cancellationException дальше?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Привет!

when (throwable) {
is CancellationException -> {
throw throwable
}
else -> {
_result.value = Result.Error(throwable)
}
}
}
}
Expand Down
27 changes: 24 additions & 3 deletions flowcats/src/main/java/otus/homework/flowcats/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
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.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

Expand All @@ -14,8 +18,25 @@ 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 {
repeatOnLifecycle(Lifecycle.State.STARTED) {
catsViewModel.resultObservable.collect { result ->
result?.let {
when (result) {
is CatsViewModel.Result.Success<*> -> {
if (result.data is Fact) {
view.populate(result.data)
}
}
is CatsViewModel.Result.Error -> {
result.throwable.message?.let {
view.showToast(it)
}
}
}
}
}
}
}
}
}
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,12 @@ class SampleInteractor(
* 6) возвращает результат
*/
fun task1(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers()
.map { it * 5 }
.filter { it >= 20 }
.filter { it % 2 == 1 }
.map { "$it won" }
.take(3)
}

/**
Expand All @@ -29,7 +34,21 @@ 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 +57,10 @@ class SampleInteractor(
* Если айтемы в одно из флоу кончились то результирующий флоу также должен закончится
*/
fun task3(): Flow<Pair<String, String>> {
return flowOf()
val colorsFlow = sampleRepository.produceColors()
val formsFlow = sampleRepository.produceForms()

return colorsFlow.zip(formsFlow) { f1, f2 -> Pair(f1, f2) }
}

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