package com.example.background.fcm import android.content.Context import androidx.annotation.WorkerThreadimport com.google.firebase.iid.FirebaseInstanceId import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers.IOimport kotlinx.coroutines.async import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class TokenManager(scope: CoroutineScope = CoroutineScope(IO)) { private val instanceId = FirebaseInstanceId.getInstance().instanceId var currentToken: Deferredinit { currentToken = scope.async { instanceId.awaitTask()?.token } } @WorkerThread internal suspend fun share(appContext: Context) { decorateToken { deferredToken = currentToken context = appContext } } }
-----------------
import com.google.android.gms.tasks.Task import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine suspend fun <T> Task<T>.awaitTask(): T? = suspendCoroutine { continuation -> this.addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(task.result) } else { continuation.resumeWithException(task.exception!!) } }}------------------import android.content.Contextimport androidx.annotation.WorkerThreadimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Deferredimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.launch class TokenDecorator(private val scope : CoroutineScope = CoroutineScope(Dispatchers.IO)) { lateinit var deferredToken : Deferredlateinit var context : Context @WorkerThread fun decorate() { scope.launch { val token = deferredToken?.await().toString() //share with third party //sendToServer(token) } } } fun decorateToken(block : TokenDecorator.() -> Unit) = TokenDecorator().apply(block).decorate()