Skip to content

Instantly share code, notes, and snippets.

View hiteshchopra11's full-sized avatar

Hitesh Chopra hiteshchopra11

View GitHub Profile
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
PreviewParameterDemoTheme {
Greeting(name = "viewers")
}
}
}
}
suspend fun fetchImages(): Result {
return withContext(Dispatchers.IO) {
try {
val result = ImageService.create().getImages()
Result.SuccessWithData(result)
} catch (exception: Exception) {
Result.Error(exception)
}
}
}
public class HttpClient(
public val engine: HttpClientEngine,
private val userConfig: HttpClientConfig<out HttpClientEngineConfig> = HttpClientConfig()
) : {
init {
with(userConfig) {
config.install(HttpRequestLifecycle)
config.install(BodyProgress)
if (useDefaultTransformers) {
interface ImageService {
suspend fun getImages(): ImageResponse
companion object {
@ExperimentalSerializationApi fun create(): ImageService {
return ImageServiceImpl(
client = HttpClient(Android) {
install(Logging)
install(JsonFeature) {
serializer = GsonSerializer()
class ImageServiceImpl(
private val client: HttpClient
) : ImageService {
override suspend fun getImages(): ImageResponse {
return client.get {
headers {
append(HttpHeaders.Authorization, "Client-ID ${BuildConfig.CLIENT_ID}")
}
url(HttpRoutes.FETCH_IMAGES_URL)
}
interface ImageService {
@GET("/photos?page=1")
suspend fun getImages(): ImageResponse
}
object RetrofitBuilder {
private const val BASE_URL = "https://api.unsplash.com/"
private fun getRetrofit(): Retrofit {
interface ImageService {
suspend fun getImages(): ImageResponse
}
public constructor(
owner: ViewModelStoreOwner
) : this(owner.viewModelStore, defaultFactory(owner))
val viewModel = ViewModelProvider(this)[MainActivityViewModel::class.java]
findViewById<Button>(R.id.btn_increment).setOnClickListener {
viewModel.incrementByOne()
}
viewModel.counterLiveData.observe(this) { counter ->
findViewById<TextView>(R.id.tv_counter).text = "$counter"
}
val viewModel = MainActivityViewModel()
findViewById<Button>(R.id.btn_increment).setOnClickListener {
viewModel.incrementByOne()
}
viewModel.counterLiveData.observe(this) { counter ->
findViewById<TextView>(R.id.tv_counter).text = "$counter"
}