Hi all, I am confused how to use Single with Compl...
# rx
j
Hi all, I am confused how to use Single with Completable properly. I have a get method that returns Single<Data> and a other method just do saving data and return nothing ( Completable ) Code looks like below :
Copy code
fun getUserInfo() : Single<UserInfo>

fun save(token: Token) : Completable

fun initialize() {
    getUserInfo()
        .flatMap { 
            // Get token from UserInfo : val token = userInfor.getToken()
            // Call save(token: Token) method to save data
        }
        .subscribeOn(<http://Schedulers.io|Schedulers.io>())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribeBy(
            onSuccess = {
                // HERE:  Using UserInfo to do somtehing
            },
            onError = {
                Log.d(it)
            }
        )
}
How to write code inside
flatMap
block ? ( Or is there other operator suitable with this use case?)
d
You can use `andThen`:
Copy code
.flatMap { 
            // Get token from UserInfo : val token = userInfor.getToken()
            // Call save(token: Token) method to save data: save(token).andThen(Single.just(userInfo))
        }
u
I guess the problem is, you should not use flat map for side effects.
How about
doOnNext
?
j
Copy code
.flatMap { userInfo ->
                save(userInfor.token())                    .onErrorComplete()
.toSingleDefault(userInfo)
            }
I wrote like above.
doOnNext
can not be applied because this is Single<T> . It’s emit all in one time
@uli I do not use flatmap for side effects
u
@Jason isn't
save(token)
a side effect? The name suggests, that it modifies global state