Reputation: 1053
I use a Flowable data in my method and I subscribe on it to get the result. I need to get the result from subscribe method in a way that I can make sure that the next instruction in my code will run immediately.
In my code I put the next instruction just after the subscribe method. Although I think it wont run synchronously.
override fun authenticate(route: Route?, response: Response): Request? {
var userForSave: User? = null
if(responseCount(response) >= 2) {
return null
}
userDao.getAll().map({ items -> items.first({ it.userName == user!!.userName} )})
.subscribe({ res -> userForSave = res })
// I need to make sure that the next instruction after subscribe is this
val tokenDto: TokenDto = TokenDto(token = userForSave!!.token, refreshToken = userForSave!!.refreshToken)
val refreshTokenCall = service.refreshToken(tokenDto)
val refreshResponse = refreshTokenCall.execute()
if(refreshResponse.isSuccessful) {
userForSave!!.token = refreshResponse!!.body()!!.token
userForSave!!.refreshToken = refreshResponse!!.body()!!.refreshToken
userDao.update(userForSave!!)
return response.request()
.newBuilder()
.header("Authorization", "Bearer ${userForSave!!.token}")
.build()
}
return null
}
I need to make sure that I can use "userForSave" for the next instruction.
Upvotes: 1
Views: 548
Reputation: 14183
If you need to get the first emission of the Flowable
synchronously, you can call blockingFirst()
instead of subscribe(Consumer)
. In your case it should look like this:
userForSave = userDao
.getAll()
.map({ items -> items.first({ it.userName == user!!.userName} )})
.blockingFirst()
Upvotes: 1