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

android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
compileSdkVersion 36
buildToolsVersion "34.0.0"

namespace = "otus.homework.flowcats"

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

Expand Down Expand Up @@ -46,6 +46,7 @@ dependencies {
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 'androidx.lifecycle:lifecycle-runtime-ktx:2.9.4'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.3'
}
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
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@ class CatsRepository(

fun listenForCatFacts() = flow {
while (true) {
val latestNews = catsService.getCatFact()
emit(latestNews)
try {
val fact = catsService.getCatFact()
emit(Result.Success<Fact>(fact))
} catch (e: Exception) {
emit(Result.Error(e))
}
delay(refreshIntervalMs)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import retrofit2.http.GET

interface CatsService {

@GET("random?animal_type=cat")
@GET("fact")
suspend fun getCatFact(): Fact
}
2 changes: 1 addition & 1 deletion flowcats/src/main/java/otus/homework/flowcats/CatsView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class CatsView @JvmOverloads constructor(
) : ConstraintLayout(context, attrs, defStyleAttr), ICatsView {

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

Expand Down
18 changes: 12 additions & 6 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,36 @@ 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.catch
import kotlinx.coroutines.flow.collect
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 _catsStateFlow = MutableStateFlow<Result?>(null)
val catsStateFlow: StateFlow<Result?> = _catsStateFlow.asStateFlow()

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

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
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class DiContainer {

private val retrofit by lazy {
Retrofit.Builder()
.baseUrl("https://cat-fact.herokuapp.com/facts/")
.baseUrl("https://catfact.ninja/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
Expand Down
20 changes: 2 additions & 18 deletions flowcats/src/main/java/otus/homework/flowcats/Fact.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,6 @@ package otus.homework.flowcats
import com.google.gson.annotations.SerializedName

data class Fact(
@field:SerializedName("createdAt")
val createdAt: String,
@field:SerializedName("deleted")
val deleted: Boolean,
@field:SerializedName("_id")
val id: String,
@field:SerializedName("text")
val text: String,
@field:SerializedName("source")
val source: String,
@field:SerializedName("used")
val used: Boolean,
@field:SerializedName("type")
val type: String,
@field:SerializedName("user")
val user: String,
@field:SerializedName("updatedAt")
val updatedAt: String
@field:SerializedName("fact")
val fact: String
)
23 changes: 20 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,14 @@
package otus.homework.flowcats

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import androidx.lifecycle.repeatOnLifecycle

class MainActivity : AppCompatActivity() {

Expand All @@ -14,8 +20,19 @@ 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 { result ->
result?.let {
when (it) {
is Result.Success<*> -> view.populate(it.data as Fact)
is Result.Error -> {
Toast.makeText(this@MainActivity, it.ex.message, Toast.LENGTH_SHORT).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 {
data class Success<T>(val data: T) : Result()
data class Error(val ex: Throwable) : Result()
}
49 changes: 45 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()
return sampleRepository.produceNumbers()
.map {
it.times(5)
}.filter {
it > 20
}.filter {
it % 2 != 0
}.map {
"$it won"
}.take(3)
}

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

it % 3 == 0 -> {
emit(it.toString())
emit("Fizz")
}

it % 5 == 0 -> {
emit(it.toString())
emit("Buzz")
}

else -> emit(it.toString())
}
}
}

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

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