Skip to content

Commit b77f6f8

Browse files
committed
Refactor change to make it clearer when the deserialization workaround is required.
1 parent 2a4eeee commit b77f6f8

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

core/network/src/main/kotlin/com/google/samples/apps/nowinandroid/core/network/demo/DemoNiaNetworkDataSource.kt

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ package com.google.samples.apps.nowinandroid.core.network.demo
1818

1919
import JvmUnitTestDemoAssetManager
2020
import android.os.Build.VERSION.SDK_INT
21-
import android.os.Build.VERSION_CODES.N
21+
import android.os.Build.VERSION_CODES.M
2222
import com.google.samples.apps.nowinandroid.core.network.Dispatcher
2323
import com.google.samples.apps.nowinandroid.core.network.NiaDispatchers.IO
2424
import com.google.samples.apps.nowinandroid.core.network.NiaNetworkDataSource
@@ -43,10 +43,10 @@ class DemoNiaNetworkDataSource @Inject constructor(
4343
) : NiaNetworkDataSource {
4444

4545
override suspend fun getTopics(ids: List<String>?): List<NetworkTopic> =
46-
getDemoDataFromJson(TOPICS_ASSET)
46+
getDataFromJsonFile(TOPICS_ASSET)
4747

4848
override suspend fun getNewsResources(ids: List<String>?): List<NetworkNewsResource> =
49-
getDemoDataFromJson(NEWS_ASSET)
49+
getDataFromJsonFile(NEWS_ASSET)
5050

5151
override suspend fun getTopicChangeList(after: Int?): List<NetworkChangeList> =
5252
getTopics().mapToChangeList(NetworkTopic::id)
@@ -55,18 +55,22 @@ class DemoNiaNetworkDataSource @Inject constructor(
5555
getNewsResources().mapToChangeList(NetworkNewsResource::id)
5656

5757
/**
58-
* Get Demo data form a [fileName] Json file.
58+
* Get data from the given JSON [fileName].
5959
*/
6060
@OptIn(ExperimentalSerializationApi::class)
61-
private suspend inline fun <reified T> getDemoDataFromJson(fileName: String): List<T> =
61+
private suspend inline fun <reified T> getDataFromJsonFile(fileName: String): List<T> =
6262
withContext(ioDispatcher) {
6363
assets.open(fileName).use { inputStream ->
64-
if (SDK_INT >= N) {
65-
networkJson.decodeFromStream(inputStream)
66-
} // https://github.com/Kotlin/kotlinx.serialization/issues/2457#issuecomment-1786923342
67-
else {
64+
if (SDK_INT <= M) {
65+
/**
66+
* On API 23 (M) and below we must use a workaround to avoid an exception being
67+
* thrown during deserialization. See:
68+
* https://github.com/Kotlin/kotlinx.serialization/issues/2457#issuecomment-1786923342
69+
*/
6870
inputStream.bufferedReader().use(BufferedReader::readText)
6971
.let(networkJson::decodeFromString)
72+
} else {
73+
networkJson.decodeFromStream(inputStream)
7074
}
7175
}
7276
}

0 commit comments

Comments
 (0)