-
Notifications
You must be signed in to change notification settings - Fork 247
04_Coroutines_Homework #267
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
base: development
Are you sure you want to change the base?
Changes from 4 commits
f8d679b
22f4be8
8c2cb5d
10cd92d
fb7c6cb
93337c4
7dc8573
f5fb081
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| package otus.homework.coroutines | ||
|
|
||
| import com.google.gson.annotations.SerializedName | ||
|
|
||
| data class CatImage( | ||
| @SerializedName("url") | ||
| val url: String, | ||
| @SerializedName("width") | ||
| val width: Int, | ||
| @SerializedName("height") | ||
| val height: Int, | ||
| @SerializedName("id") | ||
| val id: String | ||
| ) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| package otus.homework.coroutines | ||
|
|
||
| data class CatPresentation( | ||
| val fact: String, | ||
| val imageUrl: String | ||
| ) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,28 +1,46 @@ | ||
| package otus.homework.coroutines | ||
|
|
||
| import retrofit2.Call | ||
| import retrofit2.Callback | ||
| import retrofit2.Response | ||
| import java.net.SocketTimeoutException | ||
| import kotlinx.coroutines.CoroutineName | ||
| import kotlinx.coroutines.CoroutineScope | ||
| import kotlinx.coroutines.Dispatchers | ||
| import kotlinx.coroutines.Job | ||
| import kotlinx.coroutines.async | ||
| import kotlinx.coroutines.launch | ||
|
|
||
| class CatsPresenter( | ||
| private val catsService: CatsService | ||
| private val catsService: CatsService, | ||
| private val catsImageService: CatsImageService | ||
| ) { | ||
|
|
||
| private var _catsView: ICatsView? = null | ||
| private val presenterJob = Job() | ||
| private val presenterScope = CoroutineScope( | ||
| Dispatchers.Main + presenterJob + CoroutineName("CatsCoroutine") | ||
| ) | ||
|
|
||
| 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) { | ||
| presenterScope.launch { | ||
| try { | ||
| val factDeferred = async { catsService.getCatFact() } | ||
| val imageDeferred = async { catsImageService.getRandomCatImage() } | ||
|
|
||
| val fact = factDeferred.await() | ||
| val images = imageDeferred.await() | ||
|
|
||
| val imageUrl = images.firstOrNull()?.url | ||
| val catPresentation = CatPresentation( | ||
| fact = fact.fact, | ||
| imageUrl = imageUrl ?: "" | ||
| ) | ||
| _catsView?.populate(catPresentation) | ||
| } catch (e: SocketTimeoutException) { | ||
| _catsView?.showError("Не удалось получить ответ от сервера") | ||
| } catch (e: Exception) { | ||
This comment was marked as resolved.
Sorry, something went wrong.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Хоть CatsPresenter и не используется, поправил с учётом возможности CancellationException. |
||
| CrashMonitor.trackWarning() | ||
| _catsView?.showError(e.message ?: "Неизвестная ошибка") | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| fun attachView(catsView: ICatsView) { | ||
|
|
@@ -31,5 +49,6 @@ class CatsPresenter( | |
|
|
||
| fun detachView() { | ||
| _catsView = null | ||
| presenterJob.cancel() | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,10 +1,15 @@ | ||
| package otus.homework.coroutines | ||
|
|
||
| import retrofit2.Call | ||
| import retrofit2.http.GET | ||
|
|
||
| interface CatsService { | ||
|
|
||
| @GET("fact") | ||
| fun getCatFact() : Call<Fact> | ||
| suspend fun getCatFact(): Fact | ||
| } | ||
|
|
||
| interface CatsImageService { | ||
|
|
||
| @GET("images/search") | ||
| suspend fun getRandomCatImage(): List<CatImage> | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| package otus.homework.coroutines | ||
|
|
||
| import androidx.lifecycle.LiveData | ||
| import androidx.lifecycle.MutableLiveData | ||
| import androidx.lifecycle.ViewModel | ||
| import androidx.lifecycle.viewModelScope | ||
| import java.net.SocketTimeoutException | ||
| import kotlinx.coroutines.CoroutineExceptionHandler | ||
| import kotlinx.coroutines.CoroutineName | ||
| import kotlinx.coroutines.async | ||
| import kotlinx.coroutines.launch | ||
|
|
||
| class CatsViewModel( | ||
| private val catsService: CatsService, | ||
| private val catsImageService: CatsImageService | ||
| ) : ViewModel() { | ||
|
|
||
| private val _catsLiveData = MutableLiveData<Result<CatPresentation>>() | ||
| val catsLiveData: LiveData<Result<CatPresentation>> = _catsLiveData | ||
|
|
||
| private val exceptionHandler = CoroutineExceptionHandler { _, exception -> | ||
| CrashMonitor.trackWarning() | ||
| _catsLiveData.postValue( | ||
| Result.Error(exception as? Exception ?: Exception(exception.message)) | ||
| ) | ||
| } | ||
|
|
||
| fun loadCatData() { | ||
| viewModelScope.launch(exceptionHandler + CoroutineName("CatsCoroutine")) { | ||
| try { | ||
| val factDeferred = async { catsService.getCatFact() } | ||
| val imageDeferred = async { catsImageService.getRandomCatImage() } | ||
|
|
||
| val fact = factDeferred.await() | ||
| val images = imageDeferred.await() | ||
|
|
||
| val imageUrl = images.firstOrNull()?.url | ||
| val catPresentation = CatPresentation( | ||
| fact = fact.fact, | ||
| imageUrl = imageUrl ?: "" | ||
| ) | ||
|
|
||
| _catsLiveData.value = Result.Success(catPresentation) | ||
| } catch (_: SocketTimeoutException) { | ||
| _catsLiveData.value = Result.Error(Exception("Не удалось получить ответ от сервера")) | ||
| } catch (e: Exception) { | ||
|
||
| _catsLiveData.value = Result.Error(e) | ||
| } | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| package otus.homework.coroutines | ||
|
|
||
| sealed class Result<out T> { | ||
| data class Success<T>(val data: T) : Result<T>() | ||
| data class Error(val exception: Exception) : Result<Nothing>() | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
минорно, но лучше выносить в ресурсы
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вынес, и во ViewModel тоже.
Строковый ресурс, чтобы Context не тащить во ViewModel, через фабрику корректно передавать?
Или существуют способы изящнее?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
в целом я бы так не делал, но для домашки вполне рабочий вариант) можно обойтись без контекста, вынеся получение строк в какой то provider, в котором будет контекст уже