Skip to content

Instantly share code, notes, and snippets.

View douglasiacovelli's full-sized avatar

Douglas Iacovelli douglasiacovelli

  • @contratadome
  • Bertioga
View GitHub Profile
class NetworkHelperTest {
private val dispatcher = TestCoroutineDispatcher()
@Test
fun `when lambda returns successfully then it should emit the result as success`() {
runBlockingTest {
val lambdaResult = true
val result = safeApiCall(dispatcher) { lambdaResult }
assertEquals(ResultWrapper.Success(lambdaResult), result)
}
fun fetchData() {
viewModelScope.launch {
val redditResponse = repository.getRedditPosts()
when (redditResponse) {
is NetworkError -> showNetworkError()
is GenericError-> showGenericError(redditResponse)
is Success -> showSuccess(redditResponse.value)
}
}
}
interface Repository {
suspend fun getRedditPosts(): ResultWrapper<String>
}
class RepositoryImpl(private val service: RedditService,
private val dispatcher: CoroutineDispatcher = Dispatchers.IO) : Repository {
override suspend fun getRedditPosts(): ResultWrapper<RedditPosts> {
return safeApiCall(dispatcher) { service.getRedditPosts().toRedditPosts() }
}
suspend fun <T> safeApiCall(dispatcher: CoroutineDispatcher, apiCall: suspend () -> T): ResultWrapper<T> {
return withContext(dispatcher) {
try {
ResultWrapper.Success(apiCall.invoke())
} catch (throwable: Throwable) {
when (throwable) {
is IOException -> ResultWrapper.NetworkError
is HttpException -> {
val code = throwable.code()
val errorResponse = convertErrorBody(throwable)
sealed class ResultWrapper<out T> {
data class Success<out T>(val value: T): ResultWrapper<T>()
data class GenericError(val code: Int? = null, val error: ErrorResponse? = null): ResultWrapper<Nothing>()
object NetworkError: ResultWrapper<Nothing>()
}
{
"sections": [
{
"title": "What's your name",
"type": "form",
"fields": [
{
"type": "text",
"key": "first_name",
"hint": "Type your first name"
class WorkflowRepository(private val service: WorkflowService) {
override fun submit(answers: List<Answer>): Single<MyResponse> {
val formBody = FormBody.Builder()
answers.forEach {
formBody.add(it.key, it.value)
}
return service.submit(formBody.build())
}
}
interface WorkflowService {
@POST("/my_endpoint_to_receive_data")
fun submit(@Body data: FormBody): Single<MyResponse>
}
class MainActivity : AppCompatActivity(), SectionSubmittedListener {
private val viewPager by lazy { findViewById<ViewPager>(R.id.viewPager) }
//Added code
private val nextButton by lazy { findViewById<Button>(R.id.nextButton) }
private val allAnswers = mutableListOf<Answer>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
interface SectionSubmittedListener {
fun onSectionSubmittedWithValidAnswers(answers: List<Answer>)
}