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

homework Flow: Шихов Игорь Борисович #201

Closed
wants to merge 2 commits into from
Closed
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
13 changes: 7 additions & 6 deletions flowcats/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,18 @@ android {
}

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.activity:activity-ktx:1.2.3'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.picasso:picasso:2.71828'
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.squareup.picasso:picasso:2.71828'
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
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'
}
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)
}
40 changes: 32 additions & 8 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,54 @@ package otus.homework.flowcats

import androidx.lifecycle.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.flow
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<Fact>(value = Unit as Fact)
val catsData : StateFlow<Fact> = _catsData

init {
viewModelScope.launch {
withContext(Dispatchers.IO) {
fun collectFacts() {
viewModelScope.launch {
catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
_catsData.value = it
}
}
}

fun receiveFacts() : Flow<Result> {
return flow {
try {
catsData.collectLatest() {
it?.also {
emit(Success<Fact>(it))
}
}
}
catch (e: Exception) {
emit(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()
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
@@ -1,8 +1,16 @@
package otus.homework.flowcats

import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

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

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

catsViewModel.viewModelScope.launch {
catsViewModel.receiveFacts().collect() {
if (it is Error) {
Toast.makeText(this as Activity, it.message, Toast.LENGTH_LONG).show()
}
else {
view.populate((it as Success<Fact>).result)
}
}
}
}
}
2 changes: 1 addition & 1 deletion operators/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="otus.homework.flow">
package="otus.homework.operators">

<application
android:allowBackup="true"
Expand Down
44 changes: 40 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,16 @@ class SampleInteractor(
* 6) возвращает результат
*/
fun task1(): Flow<String> {
return flowOf()
var count : Int = 0
return flow {
sampleRepository.produceNumbers().collect() {
val n = it * 5
if ((n > 20) and ((n % 2) != 0) and (count < 3)) {
emit(n.toString() + " won")
++count
}
}
}
}

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

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

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