OnChanged of MediatorLiveData not called if Transformatons not used

128 Views Asked by At

I am following https://github.com/android/architecture-components-samples/tree/88747993139224a4bb6dbe985adf652d557de621/GithubBrowserSample for sample application. I can see that they have used NetworkBoundResource class to handle db operations and network operations.

The problem I am facing now is MediatorLiveData onChanged method not getting called if I dont use Transformations.map / Transformations.swtichMap method.

I tried using that but facing problem while using those in case of multiple inputs.

Suppose I have a request login which is required 3 parameters viz. username, password & deviceId. How can I use Transformations.map / Transformations.swtichMap in view model for multiple inputs.

Below is my viewModel code:

private var _response: MutableLiveData<Resource<LoginResponse>> = MutableLiveData()
val response: LiveData<Resource<LoginResponse>>
    get() = _response

fun login(
        username: String?,
        password: String?,
        deviceId: String?
    ) {
       _response =  repository.load(
            username, password,deviceId
        ) as MutableLiveData<Resource<LoginResponse>>
    }

Below is my load method in repository:

fun load(
        username: String?,
        password: String?,
        deviceId: String?
    ): LiveData<Resource<LoginResponse>> {
        return object :
            NetworkBoundResource<LoginResponse, LoginResponse>(appExecutors) {
            override fun saveCallResult(item: LoginResponse) {
                loginDao.insertAll(item)
            }

            override fun shouldFetch(data: LoginResponse?): Boolean {
                return data == null || data.data != null ?: true ||
                        repoListRateLimit.shouldFetch(
                            serviceRequestId
                        )
            }

            override fun loadFromDb() = loginDao.getLoginData()

            override fun createCall() = apiInterface.loginAPI(
                username = username,
                password = password,
                deviceId = deviceId
            )

            override fun onFetchFailed() {
                repoListRateLimit.reset(serviceRequestId)
            }
        }.asLiveData()
    }

I am observing response : LiveData in fragment as below:

loginViewModel.loginResponse.observe(viewLifecycleOwner, Observer {
            Log.d(TAG, "Reached")
        })

Every time I call this, onChanged method not getting called. Can anyone tell me what should be work case here? Or how can I use Transformations.map / Transformations.swtichMap with multiple inputs?

0

There are 0 best solutions below