我想获取 API 请求并将请求的数据保存到数据库。还想返回数据(即写入数据库)。我知道,这在 RxJava 中是可能的,但现在我用 Kotlin 协程编写,目前使用 Fuel 而不是 Retrofit (但差异不是那么大)。我读如何将 Fuel 与 Kotlin 协程一起使用 https://stackoverflow.com/questions/50402433/how-to-use-fuel-with-a-kotlin-coroutine,但不明白。
如何编写协程和方法?
UPDATE
比如说,我们有 Java 和 Retrofit,RxJava。然后我们就可以写代码了。
地区响应:
@AutoValue
public abstract class RegionResponse {
@SerializedName("id")
public abstract Integer id;
@SerializedName("name")
public abstract String name;
@SerializedName("countryId")
public abstract Integer countryId();
public static RegionResponse create(int id, String name, int countryId) {
....
}
...
}
Region:
data class Region(
val id: Int,
val name: String,
val countryId: Int)
Network:
public Single<List<RegionResponse>> getRegions() {
return api.getRegions();
// @GET("/regions")
// Single<List<RegionResponse>> getRegions();
}
区域存储库:
fun getRegion(countryId: Int): Single<Region> {
val dbSource = db.getRegion(countryId)
val lazyApiSource = Single.defer { api.regions }
.flattenAsFlowable { it }
.map { apiMapper.map(it) }
.toList()
.doOnSuccess { db.updateRegions(it) }
.flattenAsFlowable { it }
.filter({ it.countryId == countryId })
.singleOrError()
return dbSource
.map { dbMapper.map(it) }
.switchIfEmpty(lazyApiSource)
}
区域交互器:
class RegionInteractor(
private val repo: RegionRepository,
private val prefsRepository: PrefsRepository) {
fun getRegion(): Single<Region> {
return Single.fromCallable { prefsRepository.countryId }
.flatMap { repo.getRegion(it) }
.subscribeOn(Schedulers.io())
}
}