Android Networking MVVM dengan Kotlin Coroutines
Setelah sebelumnya membuat aplikasi android MVVM networking dengan Rx Java dan Rx Android. maka kali ini akan ganti dengan Kotlin Coroutines.setelah membuat project android baru, aktifkan data binding. kemudian tambahkan library seperti berikut.
untuk sample API nya diambil dari link berikut ini. sehingga class modelnya seperti berikut.
lanjut untuk class networkingnya bisa di cek langsung kesini. setelah class-class untuk networking siap. bisa lanjut ke viewmodel. perhatikan fungsi getListPlace() terdapat viewModelScope.launch
This file contains 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
package com.yoesuv.mycoroutinesnetworking.menu.viewmodels | |
import android.app.Application | |
import androidx.lifecycle.AndroidViewModel | |
import androidx.lifecycle.MutableLiveData | |
import androidx.lifecycle.viewModelScope | |
import com.yoesuv.mycoroutinesnetworking.menu.models.PlaceModel | |
import com.yoesuv.mycoroutinesnetworking.networks.ServiceFactory | |
import com.yoesuv.mycoroutinesnetworking.utils.logDebug | |
import com.yoesuv.mycoroutinesnetworking.utils.logError | |
import kotlinx.coroutines.launch | |
import java.lang.Exception | |
class MainViewModel(application: Application) : AndroidViewModel(application) { | |
private val restApi = ServiceFactory.create() | |
var liveDataListPlace: MutableLiveData<MutableList<PlaceModel>> = MutableLiveData() | |
fun getListPlace() { | |
viewModelScope.launch { | |
try { | |
val result = restApi.getListPlace() | |
if (result.isSuccessful) { | |
logDebug("MainViewModel # SUCCESS ${result.body()?.size}") | |
liveDataListPlace.postValue(result.body()) | |
} else { | |
logError("MainViewModel # NOT SUCCESS ${result.code()}/${result.message()}") | |
} | |
} catch (exception: Exception) { | |
logError("MainViewModel # error ${exception.message}") | |
exception.printStackTrace() | |
} | |
} | |
} | |
} |
untuk lebih lengkapnya bisa cek repository githubnya disini.
selamat mencoba.
Langganan:
Posting Komentar
(
Atom
)
Tidak ada komentar :
Posting Komentar