Skip to content

Commit 7264827

Browse files
Improve LiveData syntax
1 parent 42cde97 commit 7264827

File tree

2 files changed

+14
-9
lines changed

2 files changed

+14
-9
lines changed

app/src/main/java/guide/graphql/toc/ui/chapters/ChaptersViewModel.kt

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,18 @@ class ChaptersViewModel : ViewModel() {
2424

2525
if (response.hasErrors()) {
2626
emit(Resource.error("Response has errors" ,null))
27+
return@liveData
2728
}
28-
if (response.data?.chapters != null) {
29+
response.data?.chapters?.let{
2930
emit(Resource.success(response.data!!.chapters))
30-
} else {
31-
emit(Resource.error("Data is null" ,null))
31+
return@liveData
3232
}
33+
emit(Resource.error("Data is null" ,null))
34+
return@liveData
3335
} catch (e: ApolloException) {
3436
Log.d("ChaptersQuery", "GraphQL request failed", e)
3537
emit(Resource.error("GraphQL request failed", null))
38+
return@liveData
3639
}
3740
}
3841
}

app/src/main/java/guide/graphql/toc/ui/sections/SectionsViewModel.kt

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,20 +32,22 @@ class SectionsViewModel: ViewModel() {
3232

3333
if (response.hasErrors()) {
3434
emit(Resource.error("Response has errors" ,null))
35+
return@liveData
3536
}
36-
if (response.data?.chapter != null) {
37-
val sections = response.data!!.chapter!!.sections
37+
response.data?.chapter?.sections?.let { sections ->
3838
if (sections.size > 1) {
3939
emit(Resource.success(sections))
4040
} else {
41-
emit(Resource.error("Empty sections", null))
41+
emit(Resource.error("No sections", null))
4242
}
43-
} else {
44-
emit(Resource.error("Data is empty" ,null))
43+
return@liveData
4544
}
45+
emit(Resource.error("Chapter has no sections" ,null))
46+
return@liveData
4647
} catch (e: ApolloException) {
47-
Log.d("ChaptersQuery", "GraphQL request failed", e)
48+
Log.d("Sections Query", "GraphQL request failed", e)
4849
emit(Resource.error("GraphQL request failed", null))
50+
return@liveData
4951
}
5052
}
5153
}

0 commit comments

Comments
 (0)