Last active
August 24, 2022 11:11
-
-
Save bhavesh3005sharma/6c286cad421c03095c19e72a8cd4d826 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@AndroidEntryPoint | |
class SampleFragment : Fragment() { | |
@Inject lateinit var sampleWorker : SampleWorkerInterface | |
.... | |
.... | |
private fun sendData(input : String, onComplete: ((String?) -> Unit)?) { | |
sampleWorker.sendData(input) { responseString -> | |
// responseString : Workers' result | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@HiltWorker | |
class SampleWorker @AssistedInject constructor( | |
@Assisted context: Context, | |
@Assisted params: WorkerParameters, | |
private val sampleRepository: SampleRepository | |
) : CoroutineWorker(context, params) { | |
override suspend fun doWork(): Result { | |
super.doWork() | |
var result = Result.failure() | |
.... | |
.... | |
return result | |
} | |
} | |
class SampleWorkerImp @Inject constructor( | |
private val workManager: WorkManager | |
) : SampleWorkerInterface { | |
override fun sendData( input : String, onComplete: ((String?) -> Unit)? ) { | |
OneTimeWorkRequest.Builder(SampleWorker::class.java).apply { | |
setConstraints(constraints.build()) | |
setInputData(Data.Builder().apply { | |
putString("KEY_DATA", input) | |
}.build()) | |
}.build().main { | |
workManager.enqueue(this) | |
with(workManager.getWorkInfoByIdLiveData(id)) { | |
observeForever(object : Observer<WorkInfo> { | |
override fun onChanged(work: WorkInfo) { | |
if (work.state == WorkInfo.State.SUCCEEDED | |
|| work.state == WorkInfo.State.FAILED | |
) { | |
onComplete?.invoke( | |
work.outputData.getString("KEY_OUTPUT_DATA") | |
) | |
removeObserver(this) | |
} | |
} | |
}) | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface SampleWorkerInterface { | |
fun sendData( | |
input : String, | |
onComplete: ((String?) -> Unit)? | |
) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment