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

Homework03 - Flow Ivan Makarov #126

Open
wants to merge 4 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
6 changes: 3 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
// 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.8.22"
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.2"
classpath 'com.android.tools.build:gradle:7.4.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

// NOTE: Do not place your application dependencies here; they belong
Expand All @@ -23,4 +23,4 @@ allprojects {

task clean(type: Delete) {
delete rootProject.buildDir
}
}
24 changes: 12 additions & 12 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 33
buildToolsVersion "30.0.3"

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

Expand All @@ -34,16 +34,16 @@ android {

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.core:core-ktx:1.10.1'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'com.google.code.gson:gson:2.10'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.9.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
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'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.3'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
}
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.1'
implementation 'androidx.activity:activity-ktx:1.7.2'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.1'
}
5 changes: 3 additions & 2 deletions 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 All @@ -19,4 +20,4 @@
</activity>
</application>

</manifest>
</manifest>
37 changes: 30 additions & 7 deletions flowcats/src/main/java/otus/homework/flowcats/CatsViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,44 @@ 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.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
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 _catsFlow = MutableStateFlow<Result<Fact>>(Result.Success(createEmptyFact()))
val catsFlow = _catsFlow.asStateFlow()

private fun createEmptyFact(): Fact {
return Fact(
createdAt = "",
deleted = false,
id = "",
text = "",
source = "",
used = false,
type = "",
user = "",
updatedAt = ""
)
}

init {
viewModelScope.launch {
withContext(Dispatchers.IO) {
catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
catsRepository.listenForCatFacts()
.map { Result.Success(it) as Result<Fact> }
.catch { emit(Result.Error("Ошибка соединения с сервером :(")) }
.collect {
withContext(Dispatchers.Main) {
_catsFlow.value = it
}
}
}
}
Expand All @@ -26,6 +48,7 @@ class CatsViewModel(

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
}
}
18 changes: 15 additions & 3 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,15 @@ 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 {
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
catsViewModel.catsFlow.collect {
when (it) {
is Result.Success -> view.populate(it.data)
is Result.Error -> Toast.makeText(this@MainActivity, it.message, Toast.LENGTH_LONG).show()
}
}
}
}
}
}
}
6 changes: 6 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,6 @@
package otus.homework.flowcats

sealed class Result<out T> {
data class Success<T>(val data: T): Result<T>()
data class Error(val message: String) : Result<Nothing>()
}
4 changes: 2 additions & 2 deletions gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#Wed May 05 23:18:49 MSK 2021
#Wed Jul 12 14:12:10 MSK 2023
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip
42 changes: 37 additions & 5 deletions operators/src/main/java/otus/homework/flow/SampleInteractor.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package otus.homework.flow

import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.*

@ExperimentalCoroutinesApi
Expand All @@ -18,7 +19,12 @@ class SampleInteractor(
* 6) возвращает результат
*/
fun task1(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers()
.map { it * 5 }
.filterNot { it <= 20 }
.filterNot { it % 2 == 0 }
.map { "$it won" }
.take(3)
}

/**
Expand All @@ -28,8 +34,21 @@ class SampleInteractor(
* Если входное число делится на 15 - эмитим само число и после него эмитим строку FizzBuzz
* Если число не делится на 3,5,15 - эмитим само число
*/
@OptIn(FlowPreview::class)
fun task2(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers()
.flatMapConcat { number ->
flow {
emit(number.toString())
if (number % 15 == 0) {
emit("FizzBuzz")
} else if (number % 3 == 0) {
emit("Fizz")
} else if (number % 5 == 0) {
emit("Buzz")
}
}
}
}

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