The Code A is from offical sample code here.
1: What does ++requestCount mean? Normally I use requestCount++.
2: I comprehend that the author use the fun shouldRandomlyFail() to simulate a real network, the author think that it returns True sometimes and it returns False sometimes.
But I don't think the fun shouldRandomlyFail() will work as the author expected, you know that requestCount is locale variable and never save data, so fun shouldRandomlyFail() will return fixed value. Am I right?
Code A
class FakePostsRepository : PostsRepository {
override suspend fun getPosts(): Result<List<Post>> {
return withContext(Dispatchers.IO) {
delay(800) // pretend we're on a slow network
if (shouldRandomlyFail()) {
Result.Error(IllegalStateException())
} else {
Result.Success(posts)
}
}
}
private var requestCount = 0
/**
* Randomly fail some loads to simulate a real network.
*
* This will fail deterministically every 5 requests
*/
private fun shouldRandomlyFail(): Boolean = ++requestCount % 5 == 0
}