1

如何在没有生命周期的类(如存储库)中使用新的 Kotlin v1.3 协程?我有一个类,我检查缓存是否过期,然后决定是从远程 API 还是本地数据库中获取数据。我需要从launch那里开始async。但是那我怎么取消工作呢?

示例代码:

class NotesRepositoryImpl @Inject constructor(
     private val cache: CacheDataSource,
     private val remote: RemoteDataSource
 ) : NotesRepository, CoroutineScope {

private val expirationInterval = 60 * 10 * 1000L /* 10 mins */
private val job = Job()
override val coroutineContext: CoroutineContext
    get() = Dispatchers.IO + job

override fun getNotes(): LiveData<List<Note>> {
    if (isOnline() && isCacheExpired()) {
        remote.getNotes(object : GetNotesCallback {
            override fun onGetNotes(data: List<Note>?) {
                data?.let {
                    launch {
                        cache.saveAllNotes(it)
                        cache.setLastCacheTime(System.currentTimeMillis())
                    }
                }
            }
        })
    }
    return cache.getNotes()
}

override fun addNote(note: Note) {
    if (isOnline()) {
        remote.createNote(note, object : CreateNoteCallback {
            override fun onCreateNote(note: Note?) {
                note?.let { launch { cache.addNote(it) } }
            }
        })
    } else {
        launch { cache.addNote(note) }
    }
}

override fun getSingleNote(id: Int): LiveData<Note> {
    if (isOnline()) {
        val liveData: MutableLiveData<Note> = MutableLiveData()
        remote.getNote(id, object : GetSingleNoteCallback {
            override fun onGetSingleNote(note: Note?) {
                note?.let {
                    liveData.value = it
                }
            }
        })
        return liveData
    }
    return cache.getSingleNote(id)
}

override fun editNote(note: Note) {
    if (isOnline()) {
        remote.updateNote(note, object : UpdateNoteCallback {
            override fun onUpdateNote(note: Note?) {
                note?.let { launch { cache.editNote(note) } }
            }
        })
    } else {
        cache.editNote(note)
    }
}

override fun delete(note: Note) {
    if (isOnline()) {
        remote.deleteNote(note.id!!, object : DeleteNoteCallback {
            override fun onDeleteNote(noteId: Int?) {
                noteId?.let { launch { cache.delete(note) } }
            }
        })
    } else {
        cache.delete(note)
    }
}

private fun isCacheExpired(): Boolean {
    var delta = 0L
    runBlocking(Dispatchers.IO) {
        val currentTime = System.currentTimeMillis()
        val lastCacheTime = async { cache.getLastCacheTime() }
        delta = currentTime - lastCacheTime.await()
    }
    Timber.d("delta: $delta")
    return delta > expirationInterval
}

private fun isOnline(): Boolean {
    val runtime = Runtime.getRuntime()
    try {
        val ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8")
        val exitValue = ipProcess.waitFor()
        return exitValue == 0
    } catch (e: IOException) {
        e.printStackTrace()
    } catch (e: InterruptedException) {
        e.printStackTrace()
    }
    return false
}

}

4

1 回答 1

3

您可以在存储库中创建一些取消方法,并从具有生命周期(Activity、Presenter 或 ViewModel)的类中调用它,例如:

class NotesRepositoryImpl @Inject constructor(
     private val cache: CacheDataSource,
     private val remote: RemoteDataSource
) : NotesRepository, CoroutineScope {

    private val job = Job()
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.IO + job

    fun cancel() {
        job.cancel()
    }

    //...

}

class SomePresenter(val repo: NotesRepository) {

    fun detachView() {
        repo.cancel()
    }
}

或者将启动协程移动到具有生命周期的某个类。

于 2019-01-01T12:49:19.130 回答