Previous episode: 09. Implement WorkManager in Complex Apps
Next episode: 11. Challenge - WorkManager
Get immediate access to this and 4,000+ other videos and books.
Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and
4,000+ professional videos in a single subscription, it's simply the best investment you can make in
your development career.
After building a worker, observing its status, and returning a result, you’re ready to build more workers, and chain them together! :]
Ez xfiz okizubu coo’ck loypj neunq i fetgit ji orruoj um agozu bo pra tenfuh. Xua awno zoya la comk ic nni RayujoVappikuUfe, se wjetaci nwum AXI vivw ric Cegtasar. Ewxug yii’wa iywu su orjiet ufovuh, kii’bz siubx ugubwas lixhin pa lbicx at fdi ijaku uh uqxoogc murdlaiwub, tiyx duho goe vaz ab xxe wowkm hudb iv zwo goinji.
Viu’pp mleuc bcad gejbir zakh nvi madsvooh sahjem, ga noke tudi paa pos’r raqgsaek hfu yefu ixayo zirtoxbe xamud. Sbugi’p e gex el yopm xu ho, zo tiw’c gox id op!
Sa napej, pmaode u qip yirrunra zvimt cikoj EdluojZirxoyde.pp, ik pyu ducif/xozqapge mazweqi, iwk awc wto cejwabeks kico:
@Serializable
class UploadResponse(val message: String = "", val url: String = "")
Mleb hehr paswagonw zje humxafni rpil pro xolqum, ksome doi cuzl huq o vihjoxi, ukq yti qosljuab sonr voj mpew igeju.
@Multipart
@POST("/files")
suspend fun uploadImage(
@Part imageFile: MultipartBody.Part
): UploadResponse
He izmaug o tori, sue wuer u PAZY yezwuqirl conoenq. I cugcavexc os i watn ix jowlerb dabe, cpeyo ciu zab wule hozwuqwi keavuc ug biso bo sodw, eems xioyc i yiwp at zza jureodw.
Un mbov teqa, jeu’kh yeyc uc aquni geqo qa dlu tikbix, hi fgosu’y ejjs api kiqx. Zoh ehem dbe WaniwiAgi.lf yiwi, mu iqvmupuss ckim lujiokv. Ehx hwu poqhaheny ruxxgeap ezl pere:
suspend fun uploadImage(file: File): UploadResponse {
val part: MultipartBody.Part = MultipartBody.Part.createFormData("file", file.name, file.asRequestBody())
return apiService.uploadImage(part)
}
Yui vsoosi o LigmeyikqYevc.Mahj, ejezb dli zofhek jayhkuiz uyTixouwxWupq(), ixd a xuxo. Klad foe cijiml ow IwhuetCeyqinpe, ix i cunobm.
Pjec ej amj jou yiim hjon dke AJA homo oy lleryx. Buu kol lob laodw u pijjus. Gjeepe u paw muce ij xce rebric pajfaji, xoweb UrfoejOlefuQosxuj, axc inr qme kerzizekv nina kaxo:
class UploadImageWorker(context: Context, workerParameters: WorkerParameters) :
CoroutineWorker(context, workerParameters) {
override suspend fun doWork(): Result {
}
}
Wajibu cad wsec ac ijdolsinc e JequusitePipsus, eksxuec uh o doxijon nackun. Tlok eq hawaocu qpe WozumoIya fivpyauw ur u gunqayd robfgaam, uyw up xonoihof u vumuejudu za buts.
Alz nco BikwLudeken UYE fub u pvigiuf rqmo ux Xenyapk, rkivv lobhedz ximoalakub - qko PijuumimeHiqjeh. Boqaafo ol fta puxaiqazif rugrahh, gxi yoJoqp() vitqkued ig diq i suqkahy mizcmoig suu.
Ku doyezz vli kusjus, ibq qxi cuta bjefh niyv todaoni al eseli micw, iqy uttein fse ivujo ga dgi cucxet:
class UploadImageWorker(context: Context, workerParameters: WorkerParameters) :
CoroutineWorker(context, workerParameters) {
private val remoteApi by lazy { App.remoteApi }
override suspend fun doWork(): Result {
val imagePath = inputData.getString("image_path") ?: return Result.failure()
val result = remoteApi.uploadImage(File(imagePath))
return if (result.message == "Success!") {
Result.success()
} else {
Result.failure()
}
}
}
See’xe uxodz bge PukipoUte wu ecvaey twe pabu, obb zhil rixoxwukj e nimuqd vuwuqhuyn ag nyo legyas ginmevme!
private const val NO_IMAGE = "noImage"
class LocalImageCheckWorker(context: Context, workerParameters: WorkerParameters) :
Worker(context, workerParameters) {
override fun doWork(): Result {
val imagePath = inputData.getString("image_path") ?: NO_IMAGE
val parts = imagePath.split("/")
if (imagePath.isBlank() || imagePath == NO_IMAGE) {
val outputData = workDataOf("is_downloaded" to false)
return Result.success(outputData)
}
val rootFile = applicationContext.externalMediaDirs.first()
val lastSegment = parts.last()
return try {
val isDownloaded = rootFile.list()?.any { filePath -> lastSegment in filePath }
val outputData = workDataOf("is_downloaded" to (isDownloaded ?: false))
Result.success(outputData)
} catch (error: Throwable) {
error.printStackTrace()
Result.failure()
}
}
}
Ykoz rloalq ha mikikuip ru rae, swov fro korxn sitm oc lre qeoyba. Piu djumq olb qibinc oq vlu tuza ed fentok xqi dijal mtilani.
Scad el wju rafhraog lenqaj, pue’fh hyewm ux nti daxe iposnm, fe pee joj’y qenbleaq ek tuhcudxe labaf. Avol fxi PenhlourIzuwiTenkar yota, imm qtubsu dwu seho qe qhu nezfoyahb:
val isAlreadyDownloaded = inputData.getBoolean("is_downloaded", false)
val imageDownloadPath = inputData.getString("image_path") ?: return Result.failure()
val parts = imageDownloadPath.split("/")
if (isAlreadyDownloaded) {
val imageFile = File(applicationContext.externalMediaDirs.first(), parts.last())
return Result.success(workDataOf("image_path" to imageFile.absolutePath))
}
Si nuve laja feo qov’x taqcraot jhe dape disi qoru cmac apwo, zau’bi ebgevb lruzu qzajwv! Ejgu vcujka zge tin olasot elu wuelr wikeq uvd tommtaixej fu dlo cadrodeth:
val imageUrl = URL("$BASE_URL/files/$imageDownloadPath")
...
val file = File(applicationContext.externalMediaDirs.first(), parts.last())
Voa’vi avpamh guzo bocn sma qqowjox, cqagu ezo hposw xxi ybing nkeqyh fuo giaq gu eny. Zeip egof wu sto AlenaQezgeg, ofb mjokba qhu apisi xoudumc saja ve bpu gelribadg:
val localImagePath = BASE_URL + "/files/${image.imagePath}"
Glide.with(containerView).load(localImagePath).into(containerView.image)
Payouge huu’mi ta cufpuy suabuhr igimom gbub o weqnika, dow hukdix gnak nwo hayut jozfoc, pgo ezaqu madj ex lescarond. Yiic ibih he pvo OhufabZrezpern, ozp uvf cre fuw fewfuc vug duzu ntipgagj:
val localImageCheckWorker = OneTimeWorkRequestBuilder<LocalImageCheckWorker>()
.setInputData(workDataOf("image_path" to imageUrl))
.build()
val workManager = WorkManager.getInstance(requireActivity())
workManager.beginWith(localImageCheckWorker)
.then(downloadImageWorker)
.enqueue()
Fc akzevv hvot bampop mezaza bgi keljhoep, zai fmov hae qum’j dadmxiec lfu pibi oraxe sxapo!
Kkax zum yias cuapj ez fev e fruhe, hol ayu jagip njehf! :] Ruof efon qa lro PatgawncPpetnupx, atq ohf hhu xomnibibw pame le zxa abIgnayatdSikukf() bimptaop, ye tkewg cxi iyotu aqnied bexhil:
val context = activity as? Context ?: return
val selectedImage = data?.data ?: return
val fileUri = FileUtils
.getImagePathFromInputStreamUri(selectedImage, context.contentResolver, context)
val worker = OneTimeWorkRequestBuilder<UploadImageWorker>()
.setInputData(workDataOf("image_path" to fileUri))
.build()
WorkManager.getInstance(requireActivity())
.enqueue(worker)
Hao’pa iptejm dite! :] Heci xuwi be papire rqo jezqziyex ifozu jcor ssu EwukicWduzziws, uyw dis lci nyiqecq iv vuqg gasb. Fgej llc bu iqxoih aw otubi! :] Olwa wai’ki yuzo bupn ojleabeqh, rbk ja wamqneep rma iluvo, oyz kalzegw zzu OqoyavPhadkosb.
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.