Skip to content

Coroutines Homework by Diana #253

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

Conversation

diana-cyber-w
Copy link

No description provided.

Copy link

@makzimi makzimi left a comment

Choose a reason for hiding this comment

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

Спасибо за работу. Написал несколько комментариев.
Давайте что сделаем:

  • уберем Responce из сетевых вызовов
  • переделаем PresenterScope. По сути даже не обязательно осздавать его как отдельный класс с методом cancel. Достаточно inplace сделать скоуп и всё.

import retrofit2.http.GET

interface CatsService {

@GET("fact")
fun getCatFact() : Call<Fact>
suspend fun getCatFact(): Response<Fact>
Copy link

Choose a reason for hiding this comment

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

Можно не писать Response. А просто
suspend fun getCatFact(): Response<Fact>
Будет проще потом обрабатывать ответ.

interface CatsImageService {

@GET("v1/images/search")
suspend fun getCatImage(): Response<List<Image>>
Copy link

Choose a reason for hiding this comment

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

Тут тоже можно не писать Response.

Comment on lines 15 to 17
fun cancel() {
job.cancel()
}
Copy link

Choose a reason for hiding this comment

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

Думаю, что не самое удачное решение.
У скоупа есть экстеншн метод который называется также
public fun CoroutineScope.cancel(message: String, cause: Throwable? = null): Unit

И здесь как минимум вы путаете с ним.

Также, если вы вызываете

presenterScope.launch то там ведь создается новая джоба. А не которая ваша тут job. И кенселить надо по-хорошему её.

Copy link

Choose a reason for hiding this comment

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

В общем. CoroutineScope лучше отменять через уже существующий метод CoroutineScope.cancel.

А отменять джобы - это отменять джобы. Там где сделали launch, там и трекайте.

override fun onStop() {
if (isFinishing) {
catsPresenter.detachView()
// catsPresenter = CatsPresenter(diContainer.catsService, diContainer.catsImageservice, this)
Copy link

Choose a reason for hiding this comment

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

Закоментированный код лучше удалять, если он не несет какойго то вопроса.

if (response.isSuccessful && response.body() != null) {
_catsView?.populate(response.body()!!)
presenterScope.coroutineContext.cancelChildren()
presenterScope.launch {
Copy link

Choose a reason for hiding this comment

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

Вот здесь создается дочерняя джоба. Ее и надо трекать.

override fun onResponse(call: Call<Fact>, response: Response<Fact>) {
if (response.isSuccessful && response.body() != null) {
_catsView?.populate(response.body()!!)
presenterScope.coroutineContext[Job]?.cancel()
Copy link

Choose a reason for hiding this comment

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

Так отменять неправильно. Так мы отменяем родительскую джобу. А надо дочернюю.

Правильно было бы написать что-то типа такого:

private var loadJob: Job? = null

fun onInitComplete() {
  loadJob?.cancel()
  loadJob = presenterScope.launch {
    …
  }
}

@makzimi makzimi closed this May 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants