I want to implement offline-last approach with Flow, first try to fetch data from remote source if it fails, for instance Retrofit throwing network exception, i want to fetch data from local source with the code below
return flow { emit(repository.fetchEntitiesFromRemote()) }
.map {
println(" getPostFlowOfflineLast() First map in thread: ${Thread.currentThread().name}")
val data = if (it.isEmpty()) {
repository.getPostEntitiesFromLocal()
} else {
repository.deletePostEntities()
repository.savePostEntity(it)
repository.getPostEntitiesFromLocal()
}
entityToPostMapper.map(data)
}
.catch { cause ->
println("❌ getPostFlowOfflineLast() FIRST catch with error: $cause, in thread: ${Thread.currentThread().name}")
flow { emit(repository.getPostEntitiesFromLocal()) }
}
.map { postList ->
println(" getPostFlowOfflineLast() Second map in thread: ${Thread.currentThread().name}")
ViewState<List<Post>>(
status = Status.SUCCESS,
data = postList
)
}
.catch { cause: Throwable ->
println("❌ getPostFlowOfflineLast() SECOND catch with error: $cause, in thread: ${Thread.currentThread().name}")
flow {
emit(
ViewState<List<Post>>(
Status.ERROR,
error = cause
)
)
}
}
But it gets stuck with exception
I: ❌ getPostFlowOfflineLast() FIRST catch with error: java.net.UnknownHostException: Unable to resolve host "jsonplaceholder.typicode.com": No address associated with hostname, in thread: main
What should be the right implementation to have any observable like with RxJava onResumeNext if repository function was an Observerable?
onErrorResumeNext { _: Throwable ->
Observable.just(repository.getPostEntitiesFromLocal())
}