简体   繁体   English

Android循环调用Rest API

[英]Android call Rest API in a loop

I'm new to android, so have some questions regarding api calls. 我是android新手,所以对api调用有一些疑问。

Currently i use Retrofit to accomplish my api calls. 目前,我使用Retrofit完成我的api调用。

Here is example of my api call with retrofit 这是经过改造的我的api调用示例

@POST("posts/new")
fun createPost(@Body post: Post, @Header("Authorization") token: String): Single<PostResult>

So, assume i have 10 posts and i need to call createPost 10 times (Yes, i know i can have list input on BE side, but ... ). 因此,假设我有10个帖子,并且我需要调用createPost 10次​​(是的,我知道我可以在BE端输入list ,但是...)。 Best way is to iterate over posts ( for/map ) and send them to the server. 最好的方法是遍历帖子( for/map )并将其发送到服务器。

But here is problem: 但是这里有问题:
- How do i can track that all calls are done? -如何跟踪所有通话已完成?

In JS i can have something like Promise.all - could i do something similar in android? 在JS中我可以有类似Promise.all东西-我可以在android中做类似的事情吗?

I thought about counting the finished vs started requests, but i think it's bit ugly isn't? 我考虑过计算已完成的请求与已开始的请求,但我认为这有点丑陋吗?

Thanks to @shkschneider 感谢@shkschneider

Your question is broad. 您的问题很广泛。 You could use RxJava to zip, or coroutines to async/await or other methods. 您可以使用RxJava进行压缩,或使用协程进行异步/等待或其他方法。

Ended up with usage of .zip 最终使用了.zip

Single.zip(observables) { args -> args }
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe({ ...Success }, { ...Failure })

in your response success you need to call again get/post method. 为了使响应成功,您需要再次调用get / post方法。 after success you know your api call is done or else it throw error. 成功后,您知道您的api调用已完成,否则会引发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM