0

In many tutorial showing, its has one LiveData (eg userId).

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

Unfortunately for me, I need 4 LiveData(eg. userEmail, passowrd, authKey, and so on... )to make a network request. Transformation.swithMap accept only one LiveData as param.

How can i solve for this situation? Thanks you!

amlwin
  • 4,059
  • 2
  • 15
  • 34
  • https://stackoverflow.com/questions/49493772/mediatorlivedata-or-switchmap-transformation-with-multiple-parameters – Raghunandan Jul 29 '18 at 05:45

1 Answers1

2

After I find a lot. I found a recommended way that use in 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
            )
        )
    }

on that snippets. onSwapClicked() need 4 variables to make an action. so they surround with if and wait variables that are not null.

amlwin
  • 4,059
  • 2
  • 15
  • 34