Search code examples
androidkotlinrx-javakotlinx.coroutinesrx-kotlin2

How to use await method inside a flatMap?


my problem is this. I have the next code

Observable.fromIterable(this)
            .flatMap { project ->
                val date = async(CommonPool) {
                    App.db.projectResponseDao().getLastUpdate(project.uid.toString())
                }
                val query = ProjectQuery.builder().id(project.uid.toString()).date(date.await()).build()
                val baseGraphQlUrl = context.getString(R.string.base_graphql_url)
                val apolloCall: ApolloCall<ProjectQuery.Data> = ApiClient.getApolloClient(context.getSessionToken(), baseGraphQlUrl).query(query)
                val remoteObservable: Observable<Pair<Project, Response<ProjectQuery.Data>>> = Observable.combineLatest(
                        Observable.just(project),
                        Rx2Apollo.from(apolloCall),
                        BiFunction { localProject, response -> Pair(localProject, response) })
                remoteObservable
            }

So, I'm getting a date from a Room table in my android application. I'm using an async method because the room queries need to be done in a different thread from UI. So, with the result, I want to build a new query to a remote database. The problem is I want to be sure that date is already initialized at the moment I create my query. With that in mind, I use await method, but an error is given to me. it said I cant call await function in a no suspend function. So, can you think of a way to solve this? or how to fix it? thank you


Solution

  • If all you are trying to do is get your Rooms call off the main thread, you can have your flatMap code run on an IO thread by adding .subscribeOn(Schedulers.io()) to the end of your code posted above. Then you don't need to move threads inside flatMap.

    Observable.fromIterable(this)
          .flatMap { project->
          val date = App.db.projectResponseDao().getLastUpdate(project.uid.toString())
          val query = ProjectQuery.builder().id(project.uid.toString()).date(date).build()
          val baseGraphQlUrl = context.getString(R.string.base_graphql_url)
          val apolloCall: ApolloCall<ProjectQuery.Data> = ApiClient.getApolloClient(context.getSessionToken(), baseGraphQlUrl).query(query)
          val remoteObservable: Observable<Pair<Project, Response<ProjectQuery.Data>>> = Observable.combineLatest(
                            Observable.just(project),
                            Rx2Apollo.from(apolloCall),
                            BiFunction { localProject, response -> Pair(localProject, response) })
          remoteObservable
          }
          .subscribeOn(Schedulers.io())