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 #207

Open
wants to merge 3 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
5 changes: 3 additions & 2 deletions flowcats/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ plugins {
}

android {
compileSdkVersion 30
compileSdkVersion 33
buildToolsVersion "30.0.3"

namespace = "otus.homework.flowcats"

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

Expand Down Expand Up @@ -48,4 +48,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.0'
}
4 changes: 3 additions & 1 deletion flowcats/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
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,7 +1,10 @@
package otus.homework.flowcats

import android.util.Log
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 @@ -10,9 +13,14 @@ class CatsRepository(

fun listenForCatFacts() = flow {
while (true) {
val latestNews = catsService.getCatFact()
emit(latestNews)
Log.d("TAGTAG", "listenForCatFacts: ")
try {
val latestNews = catsService.getCatFact()
emit(Result.Success(latestNews))
} catch (t: Throwable) {
emit(Result.Error(t))
}
delay(refreshIntervalMs)
}
}
}.flowOn(Dispatchers.IO)
}
11 changes: 8 additions & 3 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 @@ -11,12 +12,16 @@ class CatsView @JvmOverloads constructor(
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr), ICatsView {

override fun populate(fact: Fact) {
findViewById<TextView>(R.id.fact_textView).text = fact.text
override fun populate(text: String) {
findViewById<TextView>(R.id.fact_textView).text = text
}

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

interface ICatsView {

fun populate(fact: Fact)
fun populate(text: String)
}
21 changes: 13 additions & 8 deletions flowcats/src/main/java/otus/homework/flowcats/CatsViewModel.kt
Original file line number Diff line number Diff line change
@@ -1,23 +1,28 @@
package otus.homework.flowcats

import androidx.lifecycle.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collect
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 _state: MutableStateFlow<State> = MutableStateFlow(State.Initial)
val state: StateFlow<State> = _state.asStateFlow()

init {
viewModelScope.launch {
withContext(Dispatchers.IO) {
catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
catsRepository.listenForCatFacts().collect {
when (it) {
is Result.Success<*> -> (it.data as? Fact)?.let { fact ->
_state.emit(State.Success(fact.text))
}

is Result.Error -> _state.emit(State.Error(it.t.message ?: ""))
}
}
}
Expand All @@ -26,6 +31,6 @@ 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 @@ -3,6 +3,11 @@ package otus.homework.flowcats
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
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 @@ -13,9 +18,16 @@ class MainActivity : AppCompatActivity() {
super.onCreate(savedInstanceState)
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.state.collect {
when (it) {
State.Initial -> Unit
is State.Error -> view.showToast(it.text)
is State.Success -> view.populate(it.text)
}
}
}
}
}
}
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 {
data class Success<T>(val data: T) : Result()
data class Error(val t: Throwable) : Result()
}
7 changes: 7 additions & 0 deletions flowcats/src/main/java/otus/homework/flowcats/State.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package otus.homework.flowcats

sealed class State {
data object Initial : State()
data class Success(val text: String) : State()
data class Error(val text: String) : State()
}
35 changes: 31 additions & 4 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 }
.filter { it > 20 }
.filter { it % 2 != 0 }
.map { "$it won" }
.take(3)
}

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

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

return flow1.zip(flow2) { first, second ->
Pair(first, second)
}
}

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