E
E
Eugesha19982021-03-28 23:11:36
Android
Eugesha1998, 2021-03-28 23:11:36

Anroid how to write json using Retrofit2, RxJava2?

Good evening, I ran into such a problem that I can display the contents of json, but the question is how to write it to a variable?

class UserListViewModel(application: Application) : AndroidViewModel(application) {

    private val compositeDisposable = CompositeDisposable()
    
    override fun onCleared() {
        compositeDisposable.clear()
        super.onCleared()
    }

    fun fetchUserList(usersApi: UsersApi?) {

        usersApi?.let {
            compositeDisposable.add(
                usersApi.getUserList()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                        onResponse(it)
                    }, {

                    }
            ))
        }
    }

    private fun onResponse(response: UserListResponse) {

        for (user in response.users) {
            Log.d("user info:", user.userId.toString())
            Log.d("user info:", user.userFirstName)
            Log.d("user info:", user.userLastName)
            Log.d("user info:", user.userEmail)
            Log.d("user info:", user.userImgUrl)
        }
    }
}

6060e2ecee9f4754726532.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
foonfyrick, 2021-03-29
@foonfyrick

In the place where you output everything to the logs, assign it to where you need it.

D
Denis Zagaevsky, 2021-03-29
@zagayevskiy

Retrofit makes an asynchronous request to the network on a different thread. The callback executes much later than the code immediately following the call. All code that must be executed after receiving the response must be called from the callback. In your case, it must be inside the Rx chain.
fetch must return an Observable/Single and the subscription must be in custom code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question