We already know that Observable can only have one argument as its generic type. Observable
I assume that I have 2 network calls which return 2 data type: UserResponse
and WorkResponse
.
And I want to call 2 these APIs step by step, getUser then getWork.
Finally I subscribe to them and got only one data type, obviously that's WorkResponse
because getWork is the last API call in the upper stream Observable<WorkResponse>
.
But in the subscribe code block, I want to get both UserResponse
and WorkResponse
. So how can I achieve that?
1 - Some people say that I should create a container class to contain both UserResponse
and WorkResponse
then I can get these data types from that container in subcribe code block.
2 - Create a temporary variable to hold userResponse then access to it from subscibe code block, like the following:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var tempUserResponse: UserResponse? = null
Observable.just("Prepare call API")
.flatMap {
apiGetUser()
}.flatMap { userResponse ->
tempUserResponse = userResponse // Save temporarily userResponse to pass it to subscribe code block
apiGetWork()
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { workResponse ->
Log.e("TAG", "userResponse = " + tempUserResponse)
Log.e("TAG", "workResponse = " + workResponse)
}
}
private fun apiGetUser(): Observable<UserResponse> {
// Fake API to get User
return Observable.just(UserResponse())
}
private fun apiGetWork(): Observable<Work> {
// Fake API to get Work
return Observable.just(Work())
}
class Work
class UserResponse
}
3 - Is there another way? Please give me answer, thanks so much!
EDIT: Thanks for all your answers, guys! All your answers, may be different at the ways to implement (using nested flatMap
or using zip
) but we all need to use a 3rd class as a container class for all objects we need.
Built-in container classes, we have: Pair<A, B>
and Triple<A, B, C>
. If we need more arguments, we must create our own ones