首页 > 解决方案 > 如何从 mainActivity 访问变量(在协程内)?

问题描述

提前感谢您的宝贵时间!

我正在练习 API 和网络调用,所以我构建了一个小程序来从公共 API 获取玩家列表并将其显示在 recyclerView @MainActivity 中。简单的。

问题是,除了将列表从协程发送到 recyclerView 适配器之外,我还希望能够将列表存储在某个地方,以便我可以从协程外部访问它。

这样我就可以在没有网络调用的情况下使用玩家列表

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home)

        CoroutineScope(Dispatchers.IO).launch {

            // Here we store the data received in a generic type "response"
            val response = LaRojaService
                .getLaRojaDataService()
                .getLaRojaPlayers()

            // Return to UI thread to process the data and inflate the recyclerView with it
            withContext(Dispatchers.Main) {
                if (response.isSuccessful) {
                    val temp = response.body()
                    val tempList = mutableListOf<Player>()

                    var index = 0
                    temp?.forEach {
                        val active = temp[index].active
                        val bio = temp[index].bio
                        val gamesPlayed = temp[index].gamesPlayed
                        val goalsScored = temp[index].goalsScored
                        val name = temp[index].name
                        val number = temp[index].number
                        val playerPictureUrl = temp[index].playerPictureUrl
                        val position = temp[index].position
                        val profilePictureUrl = temp[index].profilePictureUrl
                        val seasonsActive = temp[index].seasonsActive

                        tempList.add(Player(active, bio, gamesPlayed, goalsScored, name,
                            number, playerPictureUrl, position, profilePictureUrl, seasonsActive))

                        index += 1
                    }
                    recyclerView_home.layoutManager = LinearLayoutManager(this@HomeActvity)
                    recyclerView_home.adapter = HomePlayerAdapter(tempList)
                }
            }
        }
    }

这是做什么的:

- Get a list of players from a public API using a coroutine
- Inflate the recyclerView with the list created on the MainThread

我需要它做什么:

- Get a list of players from the API using the coroutine
- Save the list outside the coroutine (In this case, MainActivity)
- Work through the data inside the mainActivity
- Inflate the recyclerView (From Main activity)

再次非常感谢你。我对这个话题仍然很困惑。我什至不知道这是否可能。

标签: android-studiokotlinscopekotlin-coroutines

解决方案


推荐阅读