Skip to content
Open
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
Next Next commit
Задание 1. Перейти с коллбеков на саспенд функции и корутины
  • Loading branch information
BaturinaAnna committed Aug 25, 2023
commit 19259b13488879d57d7a1771db00f6b1806be9d8
1 change: 1 addition & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,5 @@ dependencies {
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'
}
31 changes: 17 additions & 14 deletions app/src/main/java/otus/homework/coroutines/CatsPresenter.kt
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
package otus.homework.coroutines

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

class CatsPresenter(
private val catsService: CatsService
) {

private var _catsView: ICatsView? = null
private val outerScope = PresenterScope()
private lateinit var innerScope: CoroutineScope

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()!!)
}
}

override fun onFailure(call: Call<Fact>, t: Throwable) {
CrashMonitor.trackWarning()
outerScope.launch {
innerScope = CoroutineScope(Dispatchers.IO)
Copy link
Contributor

Choose a reason for hiding this comment

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

А иннер скоуп ты зачем делаешь?

try {
val catFact = innerScope.async { catsService.getCatFact() }
_catsView?.populate(catFact.await())
} catch (exc: SocketTimeoutException) {
_catsView?.makeToast("Не удалось получить ответ от сервером")
} catch (exc: Exception) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Здесь будет также пойман CancellationException, через который работает механизм отмены. Нужно его пробросить дальше, либо не ловить такой общий тип исключений

CrashMonitor.trackWarning(exc)
_catsView?.makeToast(exc.message.toString())
}
})
}
}

fun attachView(catsView: ICatsView) {
Expand All @@ -31,5 +32,7 @@ class CatsPresenter(

fun detachView() {
_catsView = null
outerScope.cancel()
innerScope.cancel()
}
}
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("fact")
fun getCatFact() : Call<Fact>
suspend fun getCatFact(): Fact
}
9 changes: 8 additions & 1 deletion app/src/main/java/otus/homework/coroutines/CatsView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import android.content.Context
import android.util.AttributeSet
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout

class CatsView @JvmOverloads constructor(
Expand All @@ -22,11 +23,17 @@ class CatsView @JvmOverloads constructor(
}

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

override fun makeToast(text: String) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show()
}
}

interface ICatsView {

fun populate(fact: Fact)

fun makeToast(text: String)
}
2 changes: 1 addition & 1 deletion app/src/main/java/otus/homework/coroutines/CrashMonitor.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ object CrashMonitor {
/**
* Pretend this is Crashlytics/AppCenter
*/
fun trackWarning() {
fun trackWarning(e: Throwable) {
}
}
22 changes: 4 additions & 18 deletions app/src/main/java/otus/homework/coroutines/Fact.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,8 @@ package otus.homework.coroutines
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,
@field:SerializedName("length")
val length: Int
)
12 changes: 12 additions & 0 deletions app/src/main/java/otus/homework/coroutines/PresenterScope.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package otus.homework.coroutines

import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlin.coroutines.CoroutineContext

class PresenterScope: CoroutineScope {

override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + CoroutineName("CatsCoroutine")
}