1
1
package otus.homework.coroutines
2
2
3
- import retrofit2.Call
4
- import retrofit2.Callback
5
- import retrofit2.Response
3
+ import kotlinx.coroutines.Dispatchers
4
+ import kotlinx.coroutines.cancel
5
+ import kotlinx.coroutines.launch
6
+ import kotlinx.coroutines.runBlocking
7
+ import java.lang.Exception
8
+ import java.net.SocketTimeoutException
6
9
7
10
class CatsPresenter (
8
11
private val catsService : CatsService
9
12
) {
10
13
11
14
private var _catsView : ICatsView ? = null
15
+ private val catsScope = PresenterScope ()
12
16
13
17
fun onInitComplete () {
14
- catsService.getCatFact().enqueue(object : Callback <Fact > {
15
-
16
- override fun onResponse (call : Call <Fact >, response : Response <Fact >) {
17
- if (response.isSuccessful && response.body() != null ) {
18
- _catsView ?.populate(response.body()!! )
18
+ runBlocking(Dispatchers .IO ) {
19
+ catsScope.launch {
20
+ try {
21
+ val response = catsService.getCatFact()
22
+ if (response.isSuccessful && response.body() != null ) {
23
+ _catsView ?.populate(response.body()!! )
24
+ }
25
+ } catch (e: Exception ) {
26
+ if (e is SocketTimeoutException ) {
27
+ _catsView ?.showToast(" Не удалось получить ответ от сервером" )
28
+ } else {
29
+ CrashMonitor .trackWarning(e.message.toString())
30
+ _catsView ?.showToast(e.message.toString())
31
+ }
19
32
}
20
33
}
21
-
22
- override fun onFailure (call : Call <Fact >, t : Throwable ) {
23
- CrashMonitor .trackWarning()
24
- }
25
- })
34
+ }
26
35
}
27
36
28
37
fun attachView (catsView : ICatsView ) {
@@ -32,4 +41,8 @@ class CatsPresenter(
32
41
fun detachView () {
33
42
_catsView = null
34
43
}
44
+
45
+ fun onStop (){
46
+ catsScope.cancel()
47
+ }
35
48
}
0 commit comments