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

Farsiyan V. Flow #91

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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 @@ -45,5 +45,6 @@ dependencies {
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-viewmodel-ktx:2.5.1'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.0-alpha02'
}
20 changes: 16 additions & 4 deletions flowcats/src/main/java/otus/homework/flowcats/CatsViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ 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.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
Expand All @@ -13,11 +15,20 @@ class CatsViewModel(
private val _catsLiveData = MutableLiveData<Fact>()
val catsLiveData: LiveData<Fact> = _catsLiveData

private val _catsStateFlow = MutableStateFlow<Result<Fact>>(Result.Success(null))
val catsStateFlow: StateFlow<Result<Fact>> = _catsStateFlow

init {
viewModelScope.launch {
withContext(Dispatchers.IO) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

У тебя коллектор получается на ИО собирает, нужно сделать так чтобы эмитились айтемы на IO, а собирались на Main

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Исправлено

catsRepository.listenForCatFacts().collect {
_catsLiveData.value = it
try {
catsRepository.listenForCatFacts().collect {
_catsStateFlow.value = Result.Success(it)
}
} catch (e: Exception) {
catsRepository.listenForCatFacts().collect {
_catsStateFlow.value = Result.Error(it)
}
}
}
}
Expand All @@ -26,6 +37,7 @@ class CatsViewModel(

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
}
}
17 changes: 15 additions & 2 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.launch
import kotlin.math.log

class MainActivity : AppCompatActivity() {

Expand All @@ -14,8 +19,16 @@ class MainActivity : AppCompatActivity() {
val view = layoutInflater.inflate(R.layout.activity_main, null) as CatsView
setContentView(view)

catsViewModel.catsLiveData.observe(this){
view.populate(it)
// catsViewModel.catsLiveData.observe(this){
// view.populate(it)
// }

lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
catsViewModel.catsStateFlow.collect {
it.data?.let { fact -> view.populate(fact) }
}
}
}
}
}
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<T>(val data:T? = null) {
class Success<T>(data: T?): Result<T>(data)
class Error<T>(data: T?): Result<T>(data)
}
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
package otus.homework.flow

import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4

import org.junit.Test
import org.junit.runner.RunWith

import org.junit.Assert.*

/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("otus.homework.flow", appContext.packageName)
}
}
//import androidx.test.platform.app.InstrumentationRegistry
//import androidx.test.ext.junit.runners.AndroidJUnit4
//
//import org.junit.Test
//import org.junit.runner.RunWith
//
//import org.junit.Assert.*
//
///**
// * Instrumented test, which will execute on an Android device.
// *
// * See [testing documentation](http://d.android.com/tools/testing).
// */
//@RunWith(AndroidJUnit4::class)
//class ExampleInstrumentedTest {
// @Test
// fun useAppContext() {
// // Context of the app under test.
// val appContext = InstrumentationRegistry.getInstrumentation().targetContext
// assertEquals("otus.homework.flow", appContext.packageName)
// }
//}
41 changes: 37 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,18 @@ class SampleInteractor(
* 6) возвращает результат
*/
fun task1(): Flow<String> {
return flowOf()
return sampleRepository.produceNumbers()
.map { element ->
element * 5
}
.filter { element ->
element > 20
element % 2 != 0
}
.map { element ->
"$element won"
}
.take(3)
}

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

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

/**
Expand All @@ -48,6 +72,15 @@ class SampleInteractor(
* При любом исходе, будь то выброс исключения или успешная отработка функции вызовите метод dotsRepository.completed()
*/
fun task4(): Flow<Int> {
return flowOf()
return flow {
sampleRepository.produceNumbers().catch {
if (it is IllegalArgumentException) emit(-1)
else throw it
}.onCompletion {
sampleRepository.completed()
}.collect {
emit(it)
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
package otus.homework.flow

import io.mockk.InternalPlatformDsl.toArray
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Test
import java.util.*


@ExperimentalCoroutinesApi
Expand Down Expand Up @@ -65,8 +64,7 @@ class SampleInteractorTest {
"20",
"Buzz",
"21",
"Fizz"
)
"Fizz")
val actual = dotsInteractor.task2().toList()

assertEquals(expected, actual)
Expand All @@ -84,6 +82,7 @@ class SampleInteractorTest {
every { dotsRepository.produceForms() } returns flowOf("Circle", "Square", "Triangle")

val expected = listOf("Red" to "Circle", "Green" to "Square", "Blue" to "Triangle")

val actual = dotsInteractor.task3().toList()

assertEquals(expected, actual)
Expand Down