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

ДЗ Flow Серазитдинов И.Р. #76

Open
wants to merge 8 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.0")
}
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
14 changes: 11 additions & 3 deletions flowcats/src/main/java/otus/homework/flowcats/CatsRepository.kt
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
package otus.homework.flowcats

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn

class CatsRepository(
private val catsService: CatsService,
private val refreshIntervalMs: Long = 5000
) {

fun listenForCatFacts() = flow {
fun listenForCatFacts() = flow<Result<Fact>> {
while (true) {
val latestNews = catsService.getCatFact()
emit(latestNews)
emit(Result.Success(latestNews))
delay(refreshIntervalMs)
}
}
}.flowOn(Dispatchers.IO)
.catch { e ->
Log.d([email protected], "Error", e)
emit(Result.Error(e.message ?: "Error"))
}
}
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 error(message: String) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
}
}

interface ICatsView {

fun populate(fact: Fact)

fun error(message: String)
}
26 changes: 14 additions & 12 deletions flowcats/src/main/java/otus/homework/flowcats/CatsViewModel.kt
Original file line number Diff line number Diff line change
@@ -1,31 +1,33 @@
package otus.homework.flowcats

import androidx.lifecycle.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
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 _catsStateFlow = MutableStateFlow<Result<Fact>?>(null)
val catsStateFlow: StateFlow<Result<Fact>?> = _catsStateFlow

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

class CatsViewModelFactory(private val catsRepository: CatsRepository) :
ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T =
CatsViewModel(catsRepository) as T

override fun <T : ViewModel> create(modelClass: Class<T>): T {
return 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
@@ -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,16 @@ 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.catsStateFlow.collect {
when (it) {
is Result.Success -> view.populate(it.data)
is Result.Error -> view.error(it.message)
null -> return@collect
}
}
}
}
}
}
12 changes: 12 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,12 @@
package otus.homework.flowcats

sealed class Result<T> {

data class Success<T>(
val data: T
) : Result<T>()

data class Error<T>(
val message: String
) : Result<T>()
}
4 changes: 2 additions & 2 deletions operators/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ plugins {
}

android {
compileSdkVersion 30
compileSdkVersion 32
buildToolsVersion "30.0.3"
defaultConfig {

minSdkVersion 23
targetSdkVersion 30
targetSdkVersion 32
versionCode 1
versionName "1.0"
}
Expand Down
47 changes: 42 additions & 5 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 }
.filterNot { it <= 20 }
.filterNot { it % 2 == 0 }
.map { "$it won" }
.take(3)
}

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

private infix fun Int.isDividedBy(divider: Int): Boolean {
return this % divider == 0
}

/**
* Реализуйте функцию task3, которая объединяет эмиты из двух flow и возвращает кортеж Pair<String,String>(f1,f2),
* где f1 айтем из первого флоу, f2 айтем из второго флоу.
* Если айтемы в одно из флоу кончились то результирующий флоу также должен закончится
* Если айтемы в одном из флоу кончились, то результирующий флоу также должен закончиться
*/
fun task3(): Flow<Pair<String, String>> {
return flowOf()
return sampleRepository.produceColors()
.zip(sampleRepository.produceForms()) { i, j ->
i to j
}
}

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