0

I'm using MutableLiveData<List> for the backing field. I've tried everything but it will continue to make API calls and it never breaks out of the for loop. I'm not sure whether changing the immutable list value of MutableLiveData triggers this.

    fun getTweets(userIDs: List<Long>){
        val ids = listOf(1168929753237094400, 3456625696)
        viewModelScope.launch {
            for(id in ids){
                tweetService.getUsername(id).enqueue(object : Callback<TwitterUserResponse> {
                    override fun onResponse(call: Call<TwitterUserResponse>, response: Response<TwitterUserResponse>) {
                        val username = response.body()!!.user.username
                        tweetService.getTweets(id).enqueue(object: Callback<TwitterResponse>{
                            override fun onResponse(call: Call<TwitterResponse>, response: Response<TwitterResponse>) {
                                _tweets.value = response.body()!!.tweets.apply { forEach { it.username = username } }
                            }
                            override fun onFailure(call: Call<TwitterResponse>, t: Throwable) {}
                        })
                    }

                    override fun onFailure(call: Call<TwitterUserResponse>, t: Throwable) {}
                })
            }
        }
    }
  • 2
    The for loop is just enqueuing two calls, so it will return almost immediately. Nothing in this code is calling this function again. I suspect your live data observer is triggering this function to get called again. By the way, there's no reason to use a coroutine to call `enqueue`. But you could define `getUserName` to be a suspend function to make the code much cleaner looking when using it in a coroutine. – Tenfour04 Nov 19 '22 at 15:21

0 Answers0