我如何观察4个LiveData发出网络请求

时间:2018-07-29 05:26:23

标签: android android-architecture-components android-livedata

在许多显示的教程中,它有一个LiveData(例如userId)。

private MutableLiveData<String> userId = new MutableLiveData<>();
LiveData<Resource<List<User>>> books = Transformations.switchMap(userId, id -> repository.getAllBook(id));

不幸的是,我需要4个LiveData(例如userEmailpassowrdauthKey等)来发出网络请求。 Transformation.swithMap仅接受一个LiveData作为param

我该如何解决这种情况?谢谢!

1 个答案:

答案 0 :(得分:2)

我发现很多之后。我在Google I/O app中找到了一种推荐的使用方法。 SwapReservationViewModel.kt

var userId: String? = null

    var fromId: String? = null

    var fromTitle: String? = null

    var toId: String? = null

    var toTitle: String? = null

    //clear some stuff.....  

override fun onSwapClicked() {
        _dismissDialogAction.value = Event(true)

        val immutableUserId = userId
        val immutableFromId = fromId
        val immutableFromTitle = fromTitle
        val immutableToId = toId
        val immutableToTitle = toId
        // The user should be logged in at this point.
        if (immutableUserId == null || immutableFromId == null ||
            immutableFromTitle == null || immutableToId == null || immutableToTitle == null
        ) {
            Timber.e("Tried to replace reservations with a null user or IDs")
            return
        }
        swapActionUseCase.execute(
            SwapRequestParameters(
                immutableUserId,
                immutableFromId,
                immutableFromTitle,
                immutableToId,
                immutableToTitle
            )
        )
    }

在那段。 onSwapClicked()需要4个变量才能执行操作。因此它们被if包围,并等待不为空的变量。