Can anyone help me with this. I want to achieve so...
# coroutines
k
Can anyone help me with this. I want to achieve something like this: fisrtApiCall -> secondApiCall() -> thirdApiCall() ->.. each api call if it fails then do the next one and if it succedd then finish with a function? How can I wrap this ideas with coroutines. My current code with rx single<> is quite messy.
Copy code
getLanguage().flatMap {
    RemoteConfig.countryName = it
     //load config from remote
    getFirebaseRemote().flatMap { firebaseResponse ->
        if (firebaseResponse.isNotEmpty() && ConfigModel.newInstance(firebaseResponse)?.commonInfo != null) {
            Single.just(firebaseResponse)
        } else {
             //load config from hosting
            apiClient.getString(WallpaperURLBuilder.shared.urlServerInfo2)
        }
    }
}.flatMap{ configResponse ->
    val model = ConfigModel.newInstance(configResponse)
    if (model?.commonInfo != null) {
        localStorage.configApp = model
        Single.just(configResponse)
    } else {
        // load config from s3 amazon
        apiClient.getString(WallpaperURLBuilder.shared.urlServerInfo)
    }
}.flatMap { res ->
    // retry load config
    val model = ConfigModel.newInstance(res)
    if (model?.commonInfo != null) {
        localStorage.configApp = model
        Single.just(model)
    } else {
        FirebaseRemoteConfig.getInstance()
            .setDefaultsAsync(R.xml.remote_config_defaults)
        getFirebaseRemote().map {
            if (it == "{}") {
                getConfigFromString()
            } else if (it.contains("&quot;")) {
                ConfigModel.newInstance(it.replace("&quot;", "\""))
            } else {
                val config = ConfigModel.newInstance(res)
                if (config?.commonInfo != null) {
                    config
                } else {
                    getConfigFromString()
                }
            }
        }
    }
}
    .subscribeOn(<http://Schedulers.io|Schedulers.io>())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe({ res ->
        setupConfig(res)
    }, {
        reloadConfig()
    })
current code in Rx.
u
Copy code
var result = fisrtApiCall()
if (!result.success()) {
  result = secondApiCall()
}
if (!result.success()) {
  result = thirdApiCall()
}

withContext(Dispatchers.Main) {
  if (result.success()) {
    finishFunction(result)
  } else {
    handleFailure()
  }
}
Where
fisrtApiCall
,
secondApiCall
and
thirdApiCall
are suspend functions and `result.success()`might by any test that suites like
result?.commonInfo != null
. No need to. switch to Dispatchers.IO as this should already be done by your networking framework like retrofit/okhttp/… Btw. the same should be true for rx
❤️ 1
k
Thank you sir, I am working on it.