-
Notifications
You must be signed in to change notification settings - Fork 251
Coroutine hw #277
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?
Coroutine hw #277
Changes from 1 commit
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,12 @@ | ||
| package otus.homework.coroutines | ||
|
|
||
| import com.google.gson.annotations.SerializedName | ||
|
|
||
| data class CatImage( | ||
| @field:SerializedName("url") | ||
| val url: String, | ||
| @field:SerializedName("width") | ||
| val width: Int, | ||
| @field:SerializedName("height") | ||
| val height: Int, | ||
| ) |
| 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 | ||
| import retrofit2.http.Url | ||
|
|
||
| interface CatsService { | ||
|
|
||
| @GET("fact") | ||
| fun getCatFact() : Call<Fact> | ||
| suspend fun getCatFact() : Fact | ||
|
|
||
| @GET | ||
| suspend fun getCatImage( | ||
| @Url url: String = "https://api.thecatapi.com/v1/images/search" | ||
| ): List<CatImage> | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| package otus.homework.reactivecats | ||
|
|
||
| import androidx.lifecycle.LiveData | ||
| import androidx.lifecycle.viewModelScope | ||
| import androidx.lifecycle.MutableLiveData | ||
| import androidx.lifecycle.ViewModel | ||
| import kotlinx.coroutines.CoroutineExceptionHandler | ||
| import kotlinx.coroutines.async | ||
| import kotlinx.coroutines.launch | ||
| import otus.homework.coroutines.CatModels | ||
| import otus.homework.coroutines.CatsService | ||
| import otus.homework.coroutines.CrashMonitor | ||
|
|
||
| class CatsViewModel( | ||
| private val catsService: CatsService, | ||
| ) : ViewModel() { | ||
|
|
||
| private val _state = MutableLiveData<CatsResult>() | ||
| val state: LiveData<CatsResult> = _state | ||
|
|
||
| private val errorsHandler = CoroutineExceptionHandler { _, throwable -> | ||
| CrashMonitor.trackWarning() | ||
| _state.postValue(CatsResult.Errors(throwable)) | ||
| } | ||
|
|
||
| init { | ||
| loadData() | ||
| } | ||
|
|
||
| fun loadData() { | ||
| viewModelScope.launch(errorsHandler) { | ||
| val getCatFactDiffered = async { catsService.getCatFact() } | ||
| val getCatImageDiffered = async { catsService.getCatImage() } | ||
|
|
||
| val getCatFactResponse = getCatFactDiffered.await() | ||
| val getCatImageResponse = getCatImageDiffered.await().firstOrNull() | ||
|
|
||
| val catModelsMapper = CatModels( | ||
| fact = getCatFactResponse.fact, | ||
| url = getCatImageResponse?.url.orEmpty(), | ||
| width = getCatImageResponse?.width ?: 0,//значение не использую, но пусть будет | ||
| height = getCatImageResponse?.height ?: 0,//значение не использую, но пусть будет | ||
| ) | ||
| _state.value = CatsResult.Success(catModelsMapper) | ||
| } | ||
| } | ||
|
|
||
| sealed class CatsResult { | ||
| data class Success(val catModels: CatModels) : CatsResult() | ||
|
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. по заданию он должен быть дженериком
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. поправил |
||
| data class Errors(val e: Throwable) : CatsResult() | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,29 +2,43 @@ package otus.homework.coroutines | |
|
|
||
| import androidx.appcompat.app.AppCompatActivity | ||
| import android.os.Bundle | ||
| import android.widget.Toast | ||
| import otus.homework.reactivecats.CatsViewModel | ||
| import java.net.SocketTimeoutException | ||
| import kotlin.toString | ||
|
|
||
| class MainActivity : AppCompatActivity() { | ||
|
|
||
| lateinit var catsPresenter: CatsPresenter | ||
| //lateinit var catsPresenter: CatsPresenter | ||
|
|
||
| private val diContainer = DiContainer() | ||
|
|
||
| private val viewModel = CatsViewModel(diContainer.service) | ||
|
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. так создавать вьюмодели нельзя, она не переживет смену конфигурации корректно, или нужно использовать фабрику или например делегат
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. поправил |
||
|
|
||
| override fun onCreate(savedInstanceState: Bundle?) { | ||
| super.onCreate(savedInstanceState) | ||
|
|
||
| val view = layoutInflater.inflate(R.layout.activity_main, null) as CatsView | ||
| setContentView(view) | ||
|
|
||
| catsPresenter = CatsPresenter(diContainer.service) | ||
| view.presenter = catsPresenter | ||
| catsPresenter.attachView(view) | ||
| catsPresenter.onInitComplete() | ||
| } | ||
| view.onButtonClick = { | ||
| viewModel.loadData() | ||
| } | ||
|
|
||
| override fun onStop() { | ||
| if (isFinishing) { | ||
| catsPresenter.detachView() | ||
| setContentView(view) | ||
| viewModel.state.observe(this) { result -> | ||
| when (result) { | ||
| is CatsViewModel.CatsResult.Success -> { | ||
| view.populate(result.catModels) | ||
| } | ||
|
|
||
| is CatsViewModel.CatsResult.Errors -> { | ||
| val message = when (result.e) { | ||
| is SocketTimeoutException -> getString(R.string.timeout_error_text) | ||
| else -> result.e.toString() | ||
| } | ||
|
|
||
| Toast.makeText(this, message, Toast.LENGTH_SHORT).show() | ||
| } | ||
| } | ||
| } | ||
| super.onStop() | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| package otus.homework.coroutines | ||
|
|
||
| data class CatModels ( | ||
| val fact: String, | ||
| val url: String, | ||
| val width: Int, | ||
| val height: Int, | ||
| ) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| <resources> | ||
| <string name="app_name">Cat Facts </string> | ||
| <string name="more_facts">More Facts</string> | ||
| <string name="timeout_error_text">Не удалось получить ответ от сервера</string> | ||
| </resources> |
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.
поправил