【问题标题】:How to use Retrofit for Android to communicate with firebase cloud function?如何使用 Retrofit for Android 与 Firebase 云功能进行通信?
【发布时间】:2020-02-01 17:40:27
【问题描述】:

我想使用 google 函数从我的 Android 应用向 Google Firebase 发送请求。

因此,我在客户端定义了一个 API 接口,例如:

interface MyApi {
    /**
     * Get the list of the pots from the API
     */
    @GET("/posts")
    fun getPosts(): Observable<List<Post>>

    @POST("/addUser")
    fun addUser(@Query("name") name: String, @Query("token") token: String): Observable<User>
}

在 ModelView 中,我使用 RXJava 发送请求,例如:

subscription = Observable.fromCallable{ loveDateApi.addUser(name, token) }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe( { result -> println("Result: $result") },
                        {error -> println("Error: $error")})

我观察到的用户对象如下所示:

import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.gson.annotations.Expose

@Entity
data class User(
        @Expose
        @field:PrimaryKey
        val idUser: Int,
        @Expose
        val token: String,
        @Expose
        val name: String,
        @Expose
        val age: Int
)

我提供改造的网络模块如下所示(只是摘录):

´´´

@Provides
@Reusable
@JvmStatic
internal fun provideRetrofitInterface(): Retrofit {
    return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
            .build()
}

´´´

在服务器端,我部署的谷歌云功能如下:

exports.addUser = functions.https.onRequest(async (request:any,response:any) => {

  // read parameters from request
  const name = request.query.name
  const token = request.query.token

  const data = {
    name: name,
    age: 30,
    token: token

  }

  // use add if no doc-ID is specified else use set
  const idUser = (await db.collection(collectionUser).add(data)).id

  const newData = {
    idUser: idUser,
  }

  const userRef = db.collection(collectionUser).doc(idUser)
  await userRef.update(newData)
  const newUserRef = await userRef.get()

  response.send(newUserRef.data())
})

使用邮递员向云功能发送请求有效,但不幸的是在客户端应用程序中无效。

有什么想法吗?

【问题讨论】:

    标签: android kotlin google-cloud-functions retrofit


    【解决方案1】:

    好的,找到了解决方案。我在 fromCallabe 部分添加了 blockingFirst() 方法,所以它看起来像这样:

    subscription = Observable.fromCallable{ loveDateApi.addUser(name, token).blockingFirst() }
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe( { result -> println("Result: $result") },
                            {error -> println("Error: $error")})
    

    你知道一些 RxJava 专家的替代解决方案吗? ;)

    【讨论】:

      猜你喜欢
      • 2017-09-28
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 2019-09-09
      • 1970-01-01
      • 2019-04-26
      • 2019-12-18
      • 2018-07-10
      相关资源
      最近更新 更多