https://kotlinlang.org logo
#rx
Title
# rx
j

Jason

01/10/2020, 1:51 AM
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

Daniel Rodak

01/10/2020, 10:15 AM
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

uli

01/10/2020, 2:13 PM
I guess the problem is, you should not use flat map for side effects.
How about
doOnNext
?
j

Jason

01/14/2020, 2:31 AM
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

uli

01/14/2020, 11:29 AM
@Jason isn't
save(token)
a side effect? The name suggests, that it modifies global state
3 Views