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

Домашка #177

Open
wants to merge 1 commit 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
4 changes: 2 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
// 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.8.22'
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.2"
classpath 'com.android.tools.build:gradle:8.3.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

// NOTE: Do not place your application dependencies here; they belong
Expand Down
24 changes: 13 additions & 11 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 34
buildToolsVersion "30.0.3"

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

Expand All @@ -30,20 +30,22 @@ android {
kotlinOptions {
jvmTarget = '1.8'
}
namespace 'otus.homework.flowcats'
}

dependencies {
//noinspection GradleDependency
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.core:core-ktx:1.13.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'com.google.code.gson:gson:2.10.1'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.11.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
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 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
implementation 'androidx.activity:activity-ktx:1.9.0'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.7.0'
}
6 changes: 3 additions & 3 deletions flowcats/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="otus.homework.flowcats">
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

<uses-permission android:name="android.permission.INTERNET" />
<application
Expand All @@ -10,7 +9,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
6 changes: 3 additions & 3 deletions flowcats/src/main/java/otus/homework/flowcats/CatsView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ 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(fact: Success) {
findViewById<TextView>(R.id.fact_textView).text = fact.data.text
}
}

interface ICatsView {

fun populate(fact: Fact)
fun populate(fact: Success)
}
31 changes: 19 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,38 @@
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.asStateFlow
import kotlinx.coroutines.flow.catch
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 _cats: MutableStateFlow<Result> =
MutableStateFlow(Success(Fact("", false, "", "", "", false, "", "", "")))
val cats = _cats.asStateFlow()

init {
viewModelScope.launch {
withContext(Dispatchers.IO) {
catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
}
catsRepository.listenForCatFacts()
.catch { _cats.value = Error }
.collect {
_cats.value = Success(it)
}
}
}
}

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
}
}

sealed class Result
data class Success(val data: Fact) : Result()
object Error : Result()
16 changes: 14 additions & 2 deletions flowcats/src/main/java/otus/homework/flowcats/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ package otus.homework.flowcats

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

class MainActivity : AppCompatActivity() {

Expand All @@ -14,8 +19,15 @@ 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 {
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
catsViewModel.cats.collect{result ->
when(result){
Error -> Toast.makeText(this@MainActivity, "Не удалось получить ответ от сервера", Toast.LENGTH_SHORT).show()
is Success -> view.populate(result)
}
}
}
}
}
}
5 changes: 4 additions & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,7 @@ android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
kotlin.code.style=official
android.defaults.buildfeatures.buildconfig=true
android.nonTransitiveRClass=false
android.nonFinalResIds=false
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-all.zip
3 changes: 1 addition & 2 deletions operators/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ android {

minSdkVersion 23
targetSdkVersion 30
versionCode 1
versionName "1.0"
}

compileOptions {
Expand All @@ -21,6 +19,7 @@ android {
kotlinOptions {
jvmTarget = '1.8'
}
namespace 'otus.homework.flow'
}

dependencies {
Expand Down
3 changes: 1 addition & 2 deletions operators/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="otus.homework.flow">
xmlns:android="http://schemas.android.com/apk/res/android">

<application
android:allowBackup="true"
Expand Down
61 changes: 55 additions & 6 deletions operators/src/main/java/otus/homework/flow/SampleInteractor.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
package otus.homework.flow

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

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

/**
Expand All @@ -29,7 +45,29 @@ class SampleInteractor(
* Если число не делится на 3,5,15 - эмитим само число
*/
fun task2(): Flow<String> {
return flowOf()
return (1..21).asFlow()
.flatMapConcat {
flow {
when {
it % 15 == 0 -> {
emit("$it")
emit("FizzBuzz")
}

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

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

else -> emit("$it")
}
}
}
}

/**
Expand All @@ -38,7 +76,15 @@ class SampleInteractor(
* Если айтемы в одно из флоу кончились то результирующий флоу также должен закончится
*/
fun task3(): Flow<Pair<String, String>> {
return flowOf()
return flowOf(
"Red",
"Green",
"Blue",
"Black",
"White"
).zip(flowOf("Circle", "Square", "Triangle")) { color, shape ->
color to shape
}
}

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

Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package otus.homework.flow

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf

interface SampleRepository {

Expand Down