@@ -6,22 +6,21 @@ import android.view.View
6
6
import android.view.ViewGroup
7
7
import android.widget.Toast
8
8
import androidx.fragment.app.Fragment
9
- import androidx.fragment.app.viewModels
10
- import androidx.lifecycle.Observer
9
+ import androidx.lifecycle.lifecycleScope
11
10
import androidx.navigation.fragment.findNavController
12
11
import androidx.recyclerview.widget.DividerItemDecoration
13
12
import androidx.recyclerview.widget.LinearLayoutManager
13
+ import com.apollographql.apollo.coroutines.toDeferred
14
+ import com.apollographql.apollo.exception.ApolloException
14
15
import com.google.android.material.transition.MaterialSharedAxis
16
+ import guide.graphql.toc.ChaptersQuery
15
17
import guide.graphql.toc.R
16
- import guide.graphql.toc.data.Status
18
+ import guide.graphql.toc.data.apolloClient
17
19
import guide.graphql.toc.databinding.ChaptersFragmentBinding
18
20
19
21
class ChaptersFragment : Fragment () {
20
22
21
- private val viewModel: ChaptersViewModel by viewModels()
22
-
23
23
private lateinit var binding: ChaptersFragmentBinding
24
-
25
24
override fun onCreateView (
26
25
inflater : LayoutInflater ,
27
26
container : ViewGroup ? ,
@@ -44,7 +43,6 @@ class ChaptersFragment : Fragment() {
44
43
override fun onViewCreated (view : View , savedInstanceState : Bundle ? ) {
45
44
super .onViewCreated(view, savedInstanceState)
46
45
47
- requireActivity()
48
46
val adapter =
49
47
ChaptersAdapter (
50
48
requireContext()
@@ -69,21 +67,33 @@ class ChaptersFragment : Fragment() {
69
67
binding.chapters.addItemDecoration(itemDivider)
70
68
binding.chapters.adapter = adapter
71
69
72
- viewModel.chapterList.observe(viewLifecycleOwner, Observer { chapterListResponse ->
73
- when (chapterListResponse.status) {
74
- Status .SUCCESS -> {
75
- chapterListResponse.data?.let {
76
- adapter.updateChapters(it)
77
- }
78
- }
79
- Status .ERROR -> Toast .makeText(
80
- requireContext(),
81
- getString(R .string.graphql_error, chapterListResponse.message),
82
- Toast .LENGTH_SHORT
83
- ).show()
84
- Status .LOADING -> {
70
+ lifecycleScope.launchWhenStarted {
71
+ // Loading
72
+ try {
73
+ val response = apolloClient.query(
74
+ ChaptersQuery ()
75
+ ).toDeferred().await()
76
+ if (response.hasErrors()) {
77
+ throw Exception (" Response has errors" )
85
78
}
79
+ val chapters = response.data?.chapters ? : throw Exception (" Data is null" )
80
+ // Success
81
+ adapter.updateChapters(chapters)
82
+ } catch (e: ApolloException ) {
83
+ // Error
84
+ showErrorMessage(" GraphQL request failed" )
85
+ } catch (e: Exception ) {
86
+ showErrorMessage(e.message.orEmpty())
86
87
}
87
- })
88
+ }
89
+ }
90
+
91
+
92
+ private fun showErrorMessage (errorMessage : String ) {
93
+ Toast .makeText(
94
+ requireContext(),
95
+ getString(R .string.graphql_error, errorMessage),
96
+ Toast .LENGTH_SHORT
97
+ ).show()
88
98
}
89
99
}
0 commit comments