Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Coroutine
class FootballDataManager(private val okHttpClient: OkHttpClient) {
fun loadMatch(match: String) = GlobalScope.async {
val request = Request.Builder().url(match).build()
val response = okHttpClient.newCall(request).execute()
response.body().string()
}
}
class FootballRepository(private val footballDataManager: FootballDataManager) {
fun loadMatch(match: String, callback: RepositoryCallback<MatchResponse>) = GlobalScope.launch(Dispatchers.Main) {
val requestMatch = footballDataManager.loadMatch(match)
try {
val matchData = Gson().fromJson<MatchResponse>(requestMatch.await(), MatchResponse::class.java)
callback.onSuccess(matchData)
} catch (e: Throwable) {
callback.onError(e)
}
}
}
class MatchPresenter(private val footballRepository: FootballRepository) {
companion object {
const val NEXT_MATCH = "next"
const val LAST_MATCH = "last"
}
private var job: Job? = null
private var view: MatchView? = null
fun attachView(view: MatchView?) {
this.view = view
}
fun detachView() {
this.view = null
}
fun loadMatch(match: String, leagueId: String) {
view?.onShowLoading()
val urlMatch = when (match) {
NEXT_MATCH -> "${BuildConfig.BASE_URL}eventsnextleague.php?id=$leagueId"
LAST_MATCH -> "${BuildConfig.BASE_URL}eventspastleague.php?id=$leagueId"
else -> {
""
}
}
job = footballRepository.loadMatch(urlMatch, object : RepositoryCallback<MatchResponse> {
override fun onError(e: Throwable) {
view?.onMatchEmpty()
view?.onHideLoading()
}
override fun onSuccess(data: MatchResponse) {
data.events?.let {
if (it.size > 0) {
view?.onMatchLoaded(it)
} else {
view?.onMatchEmpty()
}
} ?: kotlin.run { view?.onMatchEmpty() }
view?.onHideLoading()
}
})
}
fun cancelJob() {
job?.let {
if (it.isActive) {
it.cancel()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.