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

Kulish D. Flow Homework #64

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
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 31
buildToolsVersion "30.0.3"

defaultConfig {
applicationId "otus.homework.flowcats"
minSdkVersion 23
targetSdkVersion 30
targetSdkVersion 31
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.4.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)
}
5 changes: 5 additions & 0 deletions flowcats/src/main/java/otus/homework/flowcats/CatsView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,14 @@ class CatsView @JvmOverloads constructor(
override fun populate(fact: Fact) {
findViewById<TextView>(R.id.fact_textView).text = fact.text
}

override fun showError(error: String) {
findViewById<TextView>(R.id.fact_textView).text = error
}
}

interface ICatsView {

fun populate(fact: Fact)
fun showError(error : String)
}
23 changes: 16 additions & 7 deletions flowcats/src/main/java/otus/homework/flowcats/CatsViewModel.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package otus.homework.flowcats

import androidx.lifecycle.*
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
Expand All @@ -10,15 +15,19 @@ class CatsViewModel(
private val catsRepository: CatsRepository
) : ViewModel() {

private val _catsLiveData = MutableLiveData<Fact>()
val catsLiveData: LiveData<Fact> = _catsLiveData
private val _catsStateFlow = MutableStateFlow<Result<Fact>>(Result.Empty("Fetching..."))
val catsStateFlow: StateFlow<Result<Fact>> = _catsStateFlow

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

Choose a reason for hiding this comment

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

а нужна ли нам смена контекста, если viewmodelscope все запускает на Main диспатчере?

Copy link
Author

Choose a reason for hiding this comment

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

Нет не нужна, забыл что viewmodelscope на Main-е )

catsRepository.listenForCatFacts()
.catch {
_catsStateFlow.emit(Result.Error(it))
}
.collect {
_catsStateFlow.emit(Result.Success(it))
}
}
}
}
Expand Down
28 changes: 25 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,13 @@
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.flow.collect
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

Expand All @@ -14,8 +19,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 {

Choose a reason for hiding this comment

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

есть еще функция launchWhenStarted из ktx пакета, немного сократит код

repeatOnLifecycle(Lifecycle.State.STARTED) {
catsViewModel.catsStateFlow.collect { value ->
when (value) {
is Result.Empty -> {
view.showError(value.message)
}
is Result.Error -> {
view.showError(
value.error.message
?: "Error occurred while fetching data."
)
}
is Result.Success -> {
view.populate(value.result)
}
}
}
}
}
}
}
7 changes: 7 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,7 @@
package otus.homework.flowcats

sealed class Result<out T> {
data class Empty(val message:String) : Result<Nothing>()
data class Success<T>(val result: T) : Result<T>()
data class Error(val error: Throwable) : Result<Nothing>()
}
32 changes: 28 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,11 @@ class SampleInteractor(
* 6) возвращает результат
*/
fun task1(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers()
.map { it * 5 }
.filter { it > 20 && it % 2 != 0 }
.map { "$it won" }
.take(3)
}

/**
Expand All @@ -29,7 +33,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 +50,9 @@ class SampleInteractor(
* Если айтемы в одно из флоу кончились то результирующий флоу также должен закончится
*/
fun task3(): Flow<Pair<String, String>> {
return flowOf()
return sampleRepository.produceColors()
.zip(sampleRepository.produceForms())
{ i1, i2 -> (i1 to i2) }
}

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