edi233
edi233

Reputation: 3031

Two Single into one chain rxjava2

I have two Single:

getFile.execute(id)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribeBy(
                        onSuccess = { fileInfo ->
                            with(fileInfo) {
                                update(id, url, email)
                            }
                        },
                        onError = {
                            view?.showError()
                        }
                )

and:

private fun update(id: Long, url: String, email: String) {
        save.execute(FileInfo(id, url, email))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribeBy(
                        onSuccess = {
                            view?.onUpdateSuccess()
                        },
                        onError = {
                            view?.showUpdateError()
                        }
                )
    }

as you can see second single use data from result the first one. Can I combine those two Single into one chain?

Upvotes: 2

Views: 1017

Answers (1)

Christopher
Christopher

Reputation: 10259

You can use flatMap to chain Singles.

getFile.execute(id)
    .flatMap({fileInfo -> save.execute(fileInfo)})
    .subscribeOn(Schedulers.io())
            .subscribeBy(
                    onSuccess = {
                        view?.onUpdateSuccess()
                    },
                    onError = {
                        view?.showUpdateError()
                    }
            )

Upvotes: 3

Related Questions