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
3 changes: 2 additions & 1 deletion flowcats/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ plugins {
}

android {
compileSdkVersion 30
compileSdk 34
buildToolsVersion "30.0.3"

namespace = "otus.homework.flowcats"
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'
implementation 'androidx.lifecycle:lifecycle-viewmodel-android:2.8.7'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.3'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
}
15 changes: 12 additions & 3 deletions flowcats/src/main/java/otus/homework/flowcats/CatsRepository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,25 @@ package otus.homework.flowcats
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow

sealed class Result {
class Success(val fact: Fact): Result()
class Error(val exception: Throwable): Result()
}

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

fun listenForCatFacts() = flow {
while (true) {
val latestNews = catsService.getCatFact()
emit(latestNews)
try {
val latestFact = catsService.getCatFact()
emit(Result.Success(latestFact))
} catch (exception: Throwable) {
emit(Result.Error(exception))
}
delay(refreshIntervalMs)
}
}
}
}
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
}
40 changes: 28 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,47 @@
package otus.homework.flowcats

import android.util.Log
import androidx.lifecycle.*
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
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 _catsFlow: MutableStateFlow<Fact?> = MutableStateFlow(null)
val catsFlow: StateFlow<Fact?> = _catsFlow

init {
viewModelScope.launch {
val handler = CoroutineExceptionHandler { _, exception ->
Log.d("init", "Exception = '$exception'")
}
viewModelScope.launch(handler) {
withContext(Dispatchers.IO) {
catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
catsRepository.listenForCatFacts().collect { result ->
when (result) {
is Result.Success -> _catsFlow.value = result.fact
is Result.Error -> _catsFlow.value = null
}
}
}
}
}
}

class CatsViewModelFactory(private val catsRepository: CatsRepository) :
ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T =
CatsViewModel(catsRepository) as T
}
companion object {
val REPOSITORY_KEY = object : CreationExtras.Key<CatsRepository> { }
val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {
val repository = this[REPOSITORY_KEY] as CatsRepository
CatsViewModel(repository)
}
}
}
}
4 changes: 2 additions & 2 deletions flowcats/src/main/java/otus/homework/flowcats/DiContainer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ class DiContainer {

private val retrofit by lazy {
Retrofit.Builder()
.baseUrl("https://cat-fact.herokuapp.com/facts/")
.baseUrl("https://catfact.ninja/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}

val service by lazy { retrofit.create(CatsService::class.java) }

val repository by lazy { CatsRepository(service) }
}
}
19 changes: 2 additions & 17 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,7 @@ 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")
@field:SerializedName("fact")
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
val length: Int
)
34 changes: 28 additions & 6 deletions flowcats/src/main/java/otus/homework/flowcats/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,42 @@ package otus.homework.flowcats

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewmodel.MutableCreationExtras
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

private val diContainer = DiContainer()
private val catsViewModel by viewModels<CatsViewModel> { CatsViewModelFactory(diContainer.repository) }

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val view = layoutInflater.inflate(R.layout.activity_main, null) as CatsView
setContentView(view)

catsViewModel.catsLiveData.observe(this){
view.populate(it)
val catsViewModel: CatsViewModel = ViewModelProvider.create(this,
factory = CatsViewModel.Factory,
extras = MutableCreationExtras().apply {
set(CatsViewModel.REPOSITORY_KEY, diContainer.repository)
}
) [CatsViewModel::class]
lifecycleScope.launch {
catsViewModel.catsFlow.collect {
if (it != null) {
view.populate(it)
} else {
showError()
}
}
}
}
}

private fun showError() {
Toast.makeText(
this@MainActivity,
getString(R.string.could_not_get_response_from_server),
Toast.LENGTH_SHORT)
.show()
}
}
1 change: 1 addition & 0 deletions flowcats/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
<resources>
<string name="app_name">Flow cats</string>
<string name="could_not_get_response_from_server">Не удалось получить ответ от сервера</string>
</resources>
40 changes: 35 additions & 5 deletions operators/src/main/java/otus/homework/flow/SampleInteractor.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
package otus.homework.flow

import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flatMapConcat
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.zip

@ExperimentalCoroutinesApi
class SampleInteractor(
Expand All @@ -18,7 +26,12 @@ class SampleInteractor(
* 6) возвращает результат
*/
fun task1(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers()
.map { it * 5 }
.filter { it > 20 }
.filter { it.rem(2) == 1 }
.map { "$it won" }
.take(3)
}

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

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

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