简体   繁体   中英

Creating Live Data for Auth Token in Account Manager

I am trying to create live data for the authToken in AccountManager .

This is how I am getting the auth token.

suspend fun Fragment.getAuthToken(): String? {
    val am: AccountManager = AccountManager.get(activity)
    val accounts: Array<out Account> = am.getAccountsByType(getAccountType())
    var authToken: String? = null
    if (accounts.isNotEmpty()) {
        val account = accounts.first()
        withContext(Dispatchers.IO) {
            authToken = am.blockingGetAuthToken(account, getAccountType(), true)
        }
    }
    return authToken
}

According to the documentation I should do something like this:

class StockLiveData(symbol: String) : LiveData<BigDecimal>() {
    private val stockManager = StockManager(symbol)

    private val listener = { price: BigDecimal ->
        value = price
    }

    override fun onActive() {
        stockManager.requestPriceUpdates(listener)
    }

    override fun onInactive() {
        stockManager.removeUpdates(listener)
    }
}

However I can't figure out how to convert the example to match my case.

According to another link you can use live-data builder for coroutine:

val token: LiveData<String> = liveData {
    val tokenValue = someYourFragment.getAuthToken() 
    emit(tokenValue)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM