Skip to content

homework_2: done #1

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

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
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: 9 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,13 @@ dependencies {
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'com.squareup.picasso:picasso:2.71828'

//coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1'

//SwipeRefreshLayout
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"

//ViewModelScope
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package otus.homework.coroutines

import com.google.gson.annotations.SerializedName

data class CatImageResponse(
@field:SerializedName("file")
val fileName: String = ""
)
51 changes: 42 additions & 9 deletions app/src/main/java/otus/homework/coroutines/CatsPresenter.kt
Original file line number Diff line number Diff line change
@@ -1,35 +1,68 @@
package otus.homework.coroutines

import kotlinx.coroutines.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.Exception
import java.net.SocketTimeoutException

class CatsPresenter(
private val catsService: CatsService
private val catsService: CatsService,
private val imageService: ImageService
) {

private var _catsView: ICatsView? = null
private val presenterScope = CoroutineScope(Dispatchers.Main + CoroutineName("CatsCoroutine"))
private var factJob: Job? = null
private var refreshJob: Job? = null

fun onInitComplete() {
catsService.getCatFact().enqueue(object : Callback<Fact> {

override fun onResponse(call: Call<Fact>, response: Response<Fact>) {
if (response.isSuccessful && response.body() != null) {
_catsView?.populate(response.body()!!)
presenterScope.launch {
factJob?.cancelAndJoin()
factJob = launch {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Почему решил создать еще одну корутину с таким же контекстом, а контекст переключил внутри? Я думаю достаточно просто переключения через withContext

try {
val result = withContext(Dispatchers.IO) {
catsService.getCatFact()
}
_catsView?.populate(result)
} catch (ex: SocketTimeoutException) {
_catsView?.showErrorDialog(ex.localizedMessage ?: "error")
Copy link
Collaborator

Choose a reason for hiding this comment

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

Можно в одном catch использовать when блок с проверкой типа исключения

}
catch (ex : Exception) {
CrashMonitor.trackWarning()
}
}
}
}

override fun onFailure(call: Call<Fact>, t: Throwable) {
CrashMonitor.trackWarning()
fun loadFactAndImage() {
presenterScope.launch {
refreshJob?.cancelAndJoin()
Copy link
Collaborator

Choose a reason for hiding this comment

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

А зачем здесь cancelAndJoin?

refreshJob = launch {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Нужна ли здесь эта корутина? Думаю можно ее опустить и сразу внутри корутины запущенной на presenterScope запускать 2 параллельные через async

val factResult = async(Dispatchers.IO) { catsService.getCatFact() }
val imageResult = async(Dispatchers.IO) { imageService.getCatImage() }
try {
val factWithImage = factResult.await().copy(image = imageResult.await().fileName)
Copy link
Collaborator

Choose a reason for hiding this comment

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

А ты уверен что в таком виде они параллельно запустятся? По-моему сначала отработает первый и потом начнет второй.

_catsView?.populate(factWithImage)
} catch (ex: SocketTimeoutException) {
_catsView?.showErrorDialog(ex.localizedMessage ?: "error")
}
catch (ex : Exception) {
CrashMonitor.trackWarning()
} finally {
_catsView?.stopRefreshing()
}
}
})
}
}

fun attachView(catsView: ICatsView) {
_catsView = catsView
}

fun detachView() {
presenterScope.cancel()
_catsView = null
}
}
3 changes: 1 addition & 2 deletions app/src/main/java/otus/homework/coroutines/CatsService.kt
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
package otus.homework.coroutines

import retrofit2.Call
import retrofit2.http.GET

interface CatsService {

@GET("random?animal_type=cat")
fun getCatFact() : Call<Fact>
suspend fun getCatFact(): Fact
}
29 changes: 26 additions & 3 deletions app/src/main/java/otus/homework/coroutines/CatsView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,54 @@ package otus.homework.coroutines

import android.content.Context
import android.util.AttributeSet
import android.widget.Button
import android.widget.TextView
import android.widget.*
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.squareup.picasso.Picasso

class CatsView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr), ICatsView {
) : FrameLayout(context, attrs, defStyleAttr), ICatsView {

var presenter :CatsPresenter? = null
private var swipeRefresh: SwipeRefreshLayout? = null

override fun onFinishInflate() {
super.onFinishInflate()
findViewById<Button>(R.id.button).setOnClickListener {
presenter?.onInitComplete()
}
swipeRefresh = findViewById(R.id.refresh_layout)
swipeRefresh?.setOnRefreshListener {
swipeRefresh?.isRefreshing = true
presenter?.loadFactAndImage()
}
}

override fun populate(fact: Fact) {
findViewById<TextView>(R.id.fact_textView).text = fact.text
if (fact.image.isNotEmpty()) {
Picasso.get().load(fact.image).into(
findViewById<ImageView>(R.id.cat_image_view)
)
Toast.makeText(this.context, fact.image, Toast.LENGTH_LONG).show()
}
}

override fun showErrorDialog(message: String) {
Toast.makeText(this.context, message, Toast.LENGTH_LONG).show()
}

override fun stopRefreshing() {
swipeRefresh?.isRefreshing = false
}
}

interface ICatsView {

fun populate(fact: Fact)
fun showErrorDialog(message: String)
fun stopRefreshing()
}
7 changes: 7 additions & 0 deletions app/src/main/java/otus/homework/coroutines/DiContainer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ class DiContainer {
.addConverterFactory(GsonConverterFactory.create())
.build()
}
private val imageRetrofit by lazy {
Retrofit.Builder()
.baseUrl("https://aws.random.cat/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}

val service by lazy { retrofit.create(CatsService::class.java) }
val imageService by lazy { imageRetrofit.create(ImageService::class.java)}
}
3 changes: 2 additions & 1 deletion app/src/main/java/otus/homework/coroutines/Fact.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@ data class Fact(
@field:SerializedName("user")
val user: String,
@field:SerializedName("updatedAt")
val updatedAt: String
val updatedAt: String,
val image: String = ""
Copy link
Collaborator

Choose a reason for hiding this comment

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

Не совсем по теме ДЗ, но я бы советовал делать отдельные 2 ДТО на респонсы и их мержить в одну которая пойдет в другой слой

)
8 changes: 8 additions & 0 deletions app/src/main/java/otus/homework/coroutines/ImageService.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package otus.homework.coroutines

import retrofit2.http.GET

interface ImageService {
@GET("meow")
suspend fun getCatImage(): CatImageResponse
}
2 changes: 1 addition & 1 deletion app/src/main/java/otus/homework/coroutines/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class MainActivity : AppCompatActivity() {
val view = layoutInflater.inflate(R.layout.activity_main, null) as CatsView
setContentView(view)

catsPresenter = CatsPresenter(diContainer.service)
catsPresenter = CatsPresenter(diContainer.service, diContainer.imageService)
view.presenter = catsPresenter
catsPresenter.attachView(view)
catsPresenter.onInitComplete()
Expand Down
58 changes: 58 additions & 0 deletions app/src/main/java/otus/homework/coroutines/MainViewModel.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package otus.homework.coroutines

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.*
import java.net.SocketTimeoutException

class MainViewModel(
private val catsService: CatsService,
private val imageService: ImageService
) : ViewModel() {

val resultLiveData = MutableLiveData<Result>()
Copy link
Collaborator

Choose a reason for hiding this comment

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

Не по теме ДЗ, но наружу должна торчать имутабельная LiveData, чтобы эмитить в нее мог только 1 источник

private var factJob: Job? = null
private var refreshJob: Job? = null
private val handler = CoroutineExceptionHandler { _, exception ->
CrashMonitor.trackWarning()
}

fun onInitComplete() {
viewModelScope.launch(Dispatchers.IO + handler) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Тебе здесь можно не переключать контекст. Достаточно переключить в withContext, иначе если бы у тебя не было метода postValue который в любом случае процессится на мейн треде, у тебя была бы ошибка

factJob?.cancelAndJoin()
Copy link
Collaborator

Choose a reason for hiding this comment

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

Можно убрать

factJob = launch {
try {
val result = withContext(Dispatchers.IO) {
catsService.getCatFact()
}
resultLiveData.postValue(Result.Success(result))
} catch (ex: SocketTimeoutException) {
resultLiveData.postValue(Result.Error(ex.localizedMessage ?: "error"))
}
}
}
}

fun loadFactAndImage() {
viewModelScope.launch(Dispatchers.IO + handler) {
refreshJob?.cancelAndJoin()
Copy link
Collaborator

Choose a reason for hiding this comment

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

Можно убрать

refreshJob = launch {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Лишняя корутина

val factResult = async { catsService.getCatFact() }
val imageResult = async { imageService.getCatImage() }
try {
val factWithImage = factResult.await().copy(image = imageResult.await().fileName)
resultLiveData.postValue(Result.Success(factWithImage))
} catch (ex: SocketTimeoutException) {
resultLiveData.postValue(Result.Error(ex.localizedMessage ?: "error"))
}
}
}
}

sealed class Result {
data class Success(val data: Fact) : Result()
data class Error(val message: String) : Result()
}

}
61 changes: 42 additions & 19 deletions app/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,47 @@
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/fact_textView"
android:textColor="@color/black"
android:textSize="24sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/more_facts"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/fact_textView" />
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:id="@+id/cat_image_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="16dp"
app:layout_constraintBottom_toTopOf="@+id/fact_textView"
app:layout_constraintDimensionRatio="1.78" />

<TextView
android:id="@+id/fact_textView"
android:textColor="@color/black"
android:textSize="24sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/more_facts"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/fact_textView" />

</androidx.constraintlayout.widget.ConstraintLayout>

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>



</otus.homework.coroutines.CatsView>