<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Manuchekhr Tursunov on Medium]]></title>
        <description><![CDATA[Stories by Manuchekhr Tursunov on Medium]]></description>
        <link>https://medium.com/@manuchekhrdev?source=rss-613bc5891dda------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F87L6xPvkAbAjiHV9FkN8w.png</url>
            <title>Stories by Manuchekhr Tursunov on Medium</title>
            <link>https://medium.com/@manuchekhrdev?source=rss-613bc5891dda------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 22:22:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manuchekhrdev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Android Birthday Setup Dialog]]></title>
            <link>https://medium.com/@manuchekhrdev/android-birthday-setup-dialog-15a5c38a8bf3?source=rss-613bc5891dda------2</link>
            <guid isPermaLink="false">https://medium.com/p/15a5c38a8bf3</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[birthday]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[dialog]]></category>
            <dc:creator><![CDATA[Manuchekhr Tursunov]]></dc:creator>
            <pubDate>Thu, 25 May 2023 11:45:29 GMT</pubDate>
            <atom:updated>2023-05-25T11:45:29.723Z</atom:updated>
            <content:encoded><![CDATA[<p>First, create a function to show the birthday setup dialog:</p><pre>private fun showBirthdayDialog() {<br>    val calendar = Calendar.getInstance()<br>    val year = calendar.get(Calendar.YEAR)<br>    val month = calendar.get(Calendar.MONTH)<br>    val day = calendar.get(Calendar.DAY_OF_MONTH)<br><br>    val datePickerDialog = DatePickerDialog(requireContext(), { _, selectedYear, selectedMonth, selectedDay -&gt;<br>        // Handle the selected date<br>        val formattedDate = formatDate(selectedYear, selectedMonth, selectedDay)<br>        editText.setText(formattedDate)<br>    }, year, month, day)<br><br>    datePickerDialog.show()<br>}<br><br>private fun formatDate(year: Int, month: Int, day: Int): String {<br>    // Format the selected date into your desired format<br>    // For example: &quot;dd/MM/yyyy&quot;<br>    val dateFormat = SimpleDateFormat(&quot;dd/MM/yyyy&quot;, Locale.getDefault())<br>    val calendar = Calendar.getInstance()<br>    calendar.set(year, month, day)<br>    return dateFormat.format(calendar.time)<br>}</pre><p>Then, in your Fragment or Activity, set a click listener on the EditText to open the birthday setup dialog:</p><pre>val editText: EditText = findViewById(R.id.editText)<br><br>editText.setOnClickListener {<br>    showBirthdayDialog()<br>}</pre><p>Make sure to replace R.id.editText with the actual ID of your EditText in the layout XML file.</p><p>When the user clicks on the EditText, the birthday setup dialog will be displayed, allowing them to select a date. Once a date is selected, it will be set as the text of the EditText in the desired format.</p><p>Remember to handle any validations or additional logic as per your requirements within the showBirthdayDialog() function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15a5c38a8bf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Access token expiration. Refresh Token. Retrofit Interceptor, Coroutines]]></title>
            <link>https://medium.com/@manuchekhrdev/access-token-expiration-refresh-token-retrofit-interceptor-coroutines-c3c75069de86?source=rss-613bc5891dda------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3c75069de86</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[refresh-token]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Manuchekhr Tursunov]]></dc:creator>
            <pubDate>Thu, 25 May 2023 11:29:55 GMT</pubDate>
            <atom:updated>2023-05-25T11:29:55.329Z</atom:updated>
            <content:encoded><![CDATA[<p>I will bring an example of implementation in Kotlin for handling token expiration and refreshing the access token using Retrofit and Coroutines:</p><p>First, create an API interface for the token refresh request:</p><pre>interface ApiService {<br>    @POST(&quot;/api/v1/users/refresh-token/&quot;)<br>    suspend fun refreshAccessToken(): TokenResponse<br>}</pre><p>Create a TokenResponse data class to represent the response from the token refresh endpoint:</p><pre>data class TokenResponse(<br>    @SerializedName(&quot;access_token&quot;) val accessToken: String,<br>    @SerializedName(&quot;expires_in&quot;) val expiresIn: Long<br>)</pre><p>Next, you can implement the token refresh logic in your network interceptor or authentication manager class:</p><pre>class AuthInterceptor(private val apiService: ApiService) : Interceptor {<br>    // Other interceptor configuration and properties<br><br>    private val sessionManager = SessionManager() // Replace with your session management class<br><br>    override fun intercept(chain: Interceptor.Chain): Response {<br>        val originalRequest = chain.request()<br>        val accessToken = sessionManager.getAccessToken()<br><br>        if (accessToken != null &amp;&amp; sessionManager.isAccessTokenExpired()) {<br>            val refreshToken = sessionManager.getRefreshToken()<br><br>            // Make the token refresh request<br>            val refreshedToken = runBlocking {<br>                val response = apiService.refreshAccessToken()<br>                // Update the refreshed access token and its expiration time in the session<br>                sessionManager.updateAccessToken(response.accessToken, response.expiresIn)<br>                response.accessToken<br>            }<br><br>            if (refreshedToken != null) {<br>                // Create a new request with the refreshed access token<br>                val newRequest = originalRequest.newBuilder()<br>                    .header(&quot;Authorization&quot;, &quot;Bearer $refreshedToken&quot;)<br>                    .build()<br><br>                // Retry the request with the new access token<br>                return chain.proceed(newRequest)<br>            }<br>        }<br><br>        // Add the access token to the request header<br>        val authorizedRequest = originalRequest.newBuilder()<br>            .header(&quot;Authorization&quot;, &quot;Bearer $accessToken&quot;)<br>            .build()<br><br>        return chain.proceed(authorizedRequest)<br>    }<br>}</pre><p>n this example, SessionManager is a class that manages the access token and its expiration time. The isAccessTokenExpired() method checks if the access token has expired based on the current time and the token&#39;s expiration time stored in the session. The getAccessToken() and getRefreshToken() methods retrieve the access token and refresh token from the session, respectively. The updateAccessToken() method updates the access token and its expiration time in the session after a successful token refresh.</p><p>Make sure to configure Retrofit with the AuthInterceptor when building the OkHttpClient:</p><pre>val okHttpClient = OkHttpClient.Builder()<br>    .addInterceptor(AuthInterceptor(apiService))<br>    // Other OkHttpClient configuration<br>    .build()<br><br>val retrofit = Retrofit.Builder()<br>    .baseUrl(BASE_URL)<br>    .client(okHttpClient)<br>    // Other Retrofit configuration<br>    .build()</pre><p>With this implementation, whenever an API request receives a 401 unauthorized response due to an expired access token, the interceptor will automatically trigger the token refresh request, update the access token in the session, and retry the original request with the refreshed access token.</p><p>Here’s an example implementation of the isAccessTokenExpired() method in SessionManager class:</p><pre>class SessionManager {<br>    // Other session management properties and methods<br><br>    private var accessToken: String? = null<br>    private var accessTokenExpirationTime: Long? = null<br><br>    // Method to check if the access token has expired<br>    fun isAccessTokenExpired(): Boolean {<br>        val currentTimeMillis = System.currentTimeMillis()<br>        return accessTokenExpirationTime != null &amp;&amp; currentTimeMillis &gt;= accessTokenExpirationTime!!<br>    }<br><br>    // Method to update the access token and its expiration time in the session<br>    fun updateAccessToken(token: String, expiresIn: Long) {<br>        accessToken = token<br>        accessTokenExpirationTime = System.currentTimeMillis() + expiresIn * 1000 // Convert expiresIn to milliseconds<br>    }<br><br>    // Other session management methods<br>}</pre><p>In this example, accessToken is the stored access token, and accessTokenExpirationTime represents the expiration time of the access token. The isAccessTokenExpired() method compares the current time (currentTimeMillis) with the expiration time to determine if the access token has expired. If accessTokenExpirationTime is not null and the current time is greater than or equal to the expiration time, it indicates that the access token has expired.</p><p>The updateAccessToken() method is responsible for updating the access token and its expiration time in the session after a successful token refresh or initial login. It takes the new access token (token) and the expiration time in seconds (expiresIn), converts the expiration time to milliseconds, and stores the updated values in the accessToken and accessTokenExpirationTime properties.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3c75069de86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips for Room DB]]></title>
            <link>https://medium.com/@manuchekhrdev/tips-for-room-db-5aeb75c677a?source=rss-613bc5891dda------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aeb75c677a</guid>
            <category><![CDATA[local-database]]></category>
            <category><![CDATA[roomdb]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Manuchekhr Tursunov]]></dc:creator>
            <pubDate>Tue, 16 May 2023 18:18:27 GMT</pubDate>
            <atom:updated>2023-05-16T18:18:27.206Z</atom:updated>
            <content:encoded><![CDATA[<p>Room is an Android library that provides an abstraction layer over SQLite database. It offers an easy-to-use, compile-time-safe, and efficient way to work with databases in Android applications. Room simplifies database operations by providing type-safe queries, automatic object mapping, and support for database migrations.</p><ul><li><strong>Define Entity Relationships:</strong><br>Use @Relation annotation to define relationships between entities.</li></ul><pre>data class UserWithPets(<br>    @Embedded val user: User,<br>    @Relation(<br>        parentColumn = &quot;userId&quot;,<br>        entityColumn = &quot;ownerId&quot;<br>    )<br>    val pets: List&lt;Pet&gt;<br>)</pre><ul><li><strong>Use Type Converters:</strong><br>Use @TypeConverter annotation to convert complex data types.</li></ul><pre>class DateConverter {<br>    @TypeConverter<br>    fun toDate(timestamp: Long): Date {<br>        return Date(timestamp)<br>    }<br><br>    @TypeConverter<br>    fun toTimestamp(date: Date): Long {<br>        return date.time<br>    }<br>}</pre><ul><li><strong>Migrate Database Schema:<br></strong>Use @Database annotation and Migration classes to handle database schema migrations.</li></ul><pre>@Database(entities = [User::class], version = 2)<br>abstract class AppDatabase : RoomDatabase() {<br>    ...<br><br>    companion object {<br>        val MIGRATION_1_2: Migration = object : Migration(1, 2) {<br>            override fun migrate(database: SupportSQLiteDatabase) {<br>                // Perform database migration logic<br>            }<br>        }<br>    }<br>}</pre><ul><li><strong>Use @Query Annotation:<br></strong>Use @Query annotation to write custom SQL queries.</li></ul><pre>@Dao<br>interface UserDao {<br>    @Query(&quot;SELECT * FROM users WHERE age &gt; :minAge&quot;)<br>    fun getUsersOlderThan(minAge: Int): List&lt;User&gt;<br>}</pre><ul><li><strong>Use LiveData or Flow:<br></strong>Use LiveData or Kotlin Flow to observe database changes and update UI accordingly.</li></ul><pre>@Dao<br>interface UserDao {<br>    @Query(&quot;SELECT * FROM users&quot;)<br>    fun getAllUsers(): LiveData&lt;List&lt;User&gt;&gt; // or Flow&lt;List&lt;User&gt;&gt;<br>}</pre><ul><li><strong>Batch Operations:</strong><br>Use @Transaction annotation to perform batch operations atomically.</li></ul><pre>@Dao<br>interface UserDao {<br>    @Transaction<br>    suspend fun updateUsers(users: List&lt;User&gt;) {<br>        // Perform batch update operation<br>    }<br>}</pre><ul><li><strong>Use Testing Support:<br></strong>Use Room’s testing support to write unit tests for database operations.</li></ul><pre>@RunWith(AndroidJUnit4::class)<br>class UserDaoTest {<br>    @get:Rule<br>    val instantTaskExecutorRule = InstantTaskExecutorRule()<br><br>    private lateinit var database: AppDatabase<br>    private lateinit var userDao: UserDao<br><br>    @Before<br>    fun setup() {<br>        val context = ApplicationProvider.getApplicationContext&lt;Context&gt;()<br>        database = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java).build()<br>        userDao = database.userDao()<br>    }<br><br>    @After<br>    fun teardown() {<br>        database.close()<br>    }<br><br>    @Test<br>    fun testGetUserById() = runBlocking {<br>        // Perform test operations<br>    }<br>}</pre><p>By following these tips, you can leverage the power of Room and enhance your database operations in Android using Kotlin. These tips help you handle entity relationships, data type conversions, migrations, custom queries, observing changes, batch operations, and testing support effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aeb75c677a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginner’s Guide to Data Structures and Algorithms in Kotlin. Part 1]]></title>
            <link>https://medium.com/@manuchekhrdev/beginners-guide-to-data-structures-and-algorithms-in-kotlin-part-1-50410cf38d7c?source=rss-613bc5891dda------2</link>
            <guid isPermaLink="false">https://medium.com/p/50410cf38d7c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Manuchekhr Tursunov]]></dc:creator>
            <pubDate>Tue, 16 May 2023 18:05:45 GMT</pubDate>
            <atom:updated>2023-05-16T18:05:45.010Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4K6AyWeF-pPmqoL9Yb2Shg.png" /></figure><h4><strong>Data Structures</strong></h4><p>Data structures refer to the way data is organized and stored in a computer’s memory. They provide efficient methods for accessing, manipulating, and storing data. Some common data structures include arrays, linked lists, stacks, queues, trees, and hash tables.</p><p>Code Example: <em>Array</em></p><pre>val numbers = arrayOf(1, 2, 3, 4, 5)</pre><p><strong><em>Explanation: </em></strong>The example creates an array of integers, which is a linear data structure that stores a fixed-size sequence of elements.</p><h4>Algorithms</h4><p>Algorithms are step-by-step procedures or processes for solving a specific problem. They provide a set of instructions to perform a certain task or operation. Algorithms can be classified into various categories such as sorting, searching, graph traversal, and more.</p><p>Code Example: <em>Bubble Sort</em></p><pre>fun bubbleSort(array: IntArray) {<br>    val n = array.size<br>    for (i in 0 until n - 1) {<br>        for (j in 0 until n - i - 1) {<br>            if (array[j] &gt; array[j + 1]) {<br>                val temp = array[j]<br>                array[j] = array[j + 1]<br>                array[j + 1] = temp<br>            }<br>        }<br>    }<br>}</pre><p>Explanation: The example demonstrates the Bubble Sort algorithm, which iteratively compares adjacent elements in an array and swaps them if they are in the wrong order. This algorithm sorts the array in ascending order.</p><h4>Time Complexity</h4><p>Time complexity is a measure of the amount of time an algorithm takes to run as a function of the input size. It describes the relationship between the input size and the number of operations performed by the algorithm. Common time complexity notations include O(1), O(n), O(log n), O(n²), and more.</p><p>Code Example:<em> Linear Search</em></p><pre>fun linearSearch(array: IntArray, target: Int): Int {<br>    for (i in array.indices) {<br>        if (array[i] == target) {<br>            return i<br>        }<br>    }<br>    return -1<br>}</pre><p><em>Explanation: </em>The linear search algorithm iterates through each element in the array and compares it with the target value. The time complexity of this algorithm is O(n), where n is the size of the array.</p><h4>Space Complexity</h4><p>Space complexity is a measure of the amount of memory an algorithm requires as a function of the input size. It describes the relationship between the input size and the additional space required by the algorithm. Common space complexity notations include O(1), O(n), O(n²), and more.</p><p>Code Example: <em>Factorial</em></p><pre>fun factorial(n: Int): Int {<br>    if (n &lt;= 1) {<br>        return 1<br>    }<br>    return n * factorial(n - 1)<br>}</pre><p><em>Explanation:</em> The factorial function recursively calculates the factorial of a given number. The space complexity of this algorithm is O(n), as each recursive call adds a new frame to the call stack.</p><p>Understanding the time and space complexity of algorithms helps in analyzing their efficiency and performance. It allows developers to make informed decisions when selecting the most appropriate algorithm for a specific problem.</p><h4>Summarize</h4><ul><li><strong>Data Structures:</strong> Data structures are the way data is organized and stored. They provide efficient methods for accessing, manipulating, and storing data.</li><li><strong>Algorithms: </strong>Algorithms are step-by-step procedures for solving problems. They provide a set of instructions to perform a specific task or operation.</li><li><strong>Time Complexity:</strong> Time complexity measures the amount of time an algorithm takes to run as a function of the input size. It describes the relationship between the input size and the number of operations performed.</li><li><strong>Space Complexity: </strong>Space complexity measures the amount of memory an algorithm requires as a function of the input size. It describes the relationship between the input size and the additional space required.</li></ul><p>In Kotlin, data structures like arrays and algorithms like sorting and searching can be implemented using code examples. Time complexity is denoted using Big O notation, such as O(1), O(n), O(log n), etc., indicating the growth rate of the algorithm’s execution time. Similarly, space complexity is also denoted using Big O notation, indicating the additional space required by the algorithm.</p><p>Understanding data structures, algorithms, time complexity, and space complexity is essential for designing efficient and performant code solutions in Kotlin. It helps in selecting the right data structure or algorithm for a specific problem and optimizing the overall performance of the application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50410cf38d7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some Useful Android Development Tools And Software]]></title>
            <link>https://medium.com/@manuchekhrdev/some-useful-android-development-tools-and-software-2f1ac552237b?source=rss-613bc5891dda------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f1ac552237b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Manuchekhr Tursunov]]></dc:creator>
            <pubDate>Tue, 16 May 2023 17:00:47 GMT</pubDate>
            <atom:updated>2023-05-16T17:00:47.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wL0rIUu1_m9dKfiintPq1g.jpeg" /></figure><p><strong>1.</strong><a href="https://developer.android.com/studio"><strong>Android Studio:</strong></a> The official IDE for Android development, providing a comprehensive development environment with tools for coding, debugging, testing, and building Android apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ZpJj3jJ0cY6hJg3CKQhzyw.jpeg" /></figure><p><strong><em>Features:</em></strong></p><ul><li><em>Intelligent Code Editor</em>: Android Studio provides a powerful code editor with features like code completion, syntax highlighting, code refactoring, and integrated debugging tools.</li><li><em>Layout Editor:</em> It includes a visual layout editor that allows you to create and preview user interfaces for your Android apps without writing XML code manually.</li><li><em>Gradle Build System:</em> Android Studio uses the Gradle build system, which provides flexibility and customization options for managing dependencies, compiling code, and creating APK files.</li><li><em>Emulator and Device Support:</em> Android Studio comes with a built-in emulator that allows you to test your apps on virtual Android devices. It also supports connecting physical devices for testing.</li><li><em>Instant Run:</em> Android Studio provides the Instant Run feature, which allows you to quickly see the changes you make to your code without having to reinstall the app.</li><li><em>Profiling and Debugging Tools:</em> It includes various profiling and debugging tools to help you optimize your app’s performance and identify and fix bugs.</li></ul><p><strong><em>Pros:</em></strong></p><ul><li><em>Official IDE:</em> Android Studio is the official IDE for Android development, providing seamless integration with the Android SDK and other development tools.</li><li><em>Rich Feature Set: </em>It offers a wide range of features and tools specifically designed for Android development, making it easier and more efficient to build Android apps.</li><li><em>Active Development and Updates:</em> Android Studio is actively developed and regularly updated by Google, ensuring compatibility with the latest Android versions and incorporating new features and improvements.</li><li><em>Community and Support:</em> It has a large and active community of Android developers, which means you can find abundant resources, tutorials, and forums to seek help and guidance.</li><li><em>Integration with Other Tools:</em> Android Studio integrates well with other tools and libraries commonly used in Android development, such as Firebase, Google Play services, and third-party libraries.</li></ul><p><strong><em>Cons:</em></strong></p><ul><li><em>Resource Intensive:</em> Android Studio can be resource-intensive, requiring a powerful computer with sufficient RAM and processing power to run smoothly.</li><li><em>Learning Curve:</em> The extensive feature set of Android Studio may require some learning and getting used to, especially for developers new to Android development.</li><li><em>Gradle Build Time:</em> The build process in Android Studio, powered by Gradle, can sometimes be slow, especially for larger projects or when there are complex build configurations.</li></ul><p><strong><em>Pricing: </em></strong><br>Android Studio is available as a free and open-source software. It does not have any associated costs, and you can download and use it without any licensing fees.</p><p>It’s important to note that while Android Studio itself is free, there may be costs associated with other services or libraries you use in your Android app development.</p><p>Overall, Android Studio is a powerful and feature-rich IDE specifically designed for Android development. Its official status, robust feature set, and integration with other Android tools make it the preferred choice for building Android apps.</p><p><strong>2. </strong><a href="https://square.github.io/retrofit/"><strong>Retrofit</strong></a><strong>: </strong>A widely used networking library that simplifies the process of making HTTP requests and handling responses. It provides a high-level API for working with RESTful APIs and supports various data formats.</p><p>Example:</p><pre>val retrofit = Retrofit.Builder()<br>    .baseUrl(&quot;https://api.example.com/&quot;)<br>    .addConverterFactory(GsonConverterFactory.create())<br>    .build()<br><br>val apiService = retrofit.create(ApiService::class.java)<br>val call = apiService.getUser(userId)<br>call.enqueue(object : Callback&lt;User&gt; {<br>    override fun onResponse(call: Call&lt;User&gt;, response: Response&lt;User&gt;) {<br>        // Handle the response<br>    }<br><br>    override fun onFailure(call: Call&lt;User&gt;, t: Throwable) {<br>        // Handle the failure<br>    }<br>})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*DV4R0kGjs1H7OMMjjLDNxA.png" /></figure><p><strong><em>Features:</em></strong></p><ul><li><em>Declarative API:</em> Retrofit allows you to define the API endpoints using simple annotations, making it easy to specify the request type, URL, headers, query parameters, and response format.</li><li><em>Request and Response Serialization:</em> Retrofit provides built-in converters that handle the serialization and deserialization of request and response bodies. It supports various data formats such as JSON, XML, and Protocol Buffers.</li><li><em>Easy Integration with RxJava and Coroutines:</em> Retrofit seamlessly integrates with RxJava and Coroutines, allowing you to use reactive and asynchronous programming patterns for handling network requests.</li><li><em>Error Handling:</em> Retrofit provides error handling mechanisms for different types of responses, such as successful responses, network errors, and server errors. It allows you to define custom error models or handle errors using built-in features.</li><li><em>Authentication Support:</em> Retrofit supports various authentication mechanisms, including OAuth, API key-based authentication, and custom authentication headers.</li><li><em>File Upload and Download:</em> Retrofit provides easy-to-use methods for uploading and downloading files from a server, allowing you to handle file operations efficiently.</li></ul><p><strong><em>Pros:</em></strong></p><ul><li><em>Simple and Intuitive:</em> Retrofit’s declarative API design makes it easy to understand and use, reducing the development time and effort.</li><li><em>Robust and Efficient:</em> Retrofit handles network operations efficiently by leveraging the power of OkHttp, making it reliable and high-performing.</li><li><em>Third-Party Library Integration:</em> Retrofit integrates seamlessly with other popular libraries like Gson or Moshi for JSON serialization, RxJava for reactive programming, and OkHttp for network operations.</li><li><em>Community Support:</em> Retrofit has a large and active community, which means you can find plenty of resources, tutorials, and sample projects to help you get started and troubleshoot any issues you encounter.</li><li><em>Wide Adoption:</em> Retrofit is widely adopted in the Android development community and is backed by Square, a reputable software company.</li></ul><p><strong><em>Cons:</em></strong></p><ul><li><em>Learning Curve:</em> While Retrofit is relatively easy to use, understanding the various concepts and configurations may require some initial learning.</li><li><em>Limited Functionality: </em>Retrofit is primarily designed for making HTTP requests and handling responses. If you require more advanced features like caching or WebSocket support, you may need to integrate additional libraries or customize Retrofit.</li></ul><p><strong><em>Pricing:</em></strong></p><p>Retrofit is an open-source library released under the Apache License 2.0. This means it is free to use and does not have any associated costs.</p><p>It’s important to note that the pricing information provided above is for Retrofit itself. However, depending on your specific project requirements, you may incur costs for other services or libraries that you integrate with Retrofit.</p><p>Overall, Retrofit is a powerful and widely-used library for handling network requests in Android applications. Its simplicity, integration capabilities, and strong community support make it a popular choice among Android developers.</p><p>3. <a href="https://github.com/bumptech/glide"><strong>Glide</strong></a><strong>:</strong> An image loading library that simplifies the process of loading and caching images in Android apps. It provides a simple API for loading images from various sources and supports features like placeholder, transformations, and caching.</p><p>Example:</p><pre>Glide.with(context)<br>    .load(imageUrl)<br>    .placeholder(R.drawable.placeholder)<br>    .centerCrop()<br>    .into(imageView)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*f82fDTCyMUyRTePMC3xuCQ.png" /></figure><p><strong><em>Features:</em></strong></p><ul><li><em>Image Loading and Caching:</em> Glide is primarily used for loading and caching images in Android applications. It supports various image formats and provides efficient memory and disk caching mechanisms.</li><li><em>Image Transformation:</em> Glide allows you to apply transformations to images, such as resizing, cropping, rotating, and applying filters.</li><li><em>Animated GIF and Video Support:</em> It provides built-in support for loading and displaying animated GIFs and videos.</li><li><em>Request Prioritization and Cancelling:</em> Glide allows you to prioritize image loading requests and cancel requests as needed.</li><li><em>Memory Optimization: </em>Glide optimizes memory usage by automatically resizing and caching images based on the target view’s size and screen density.</li><li><em>Integration with Network Libraries:</em> It seamlessly integrates with popular network libraries like OkHttp and Volley to handle network requests and caching.</li></ul><p><strong><em>Pros:</em></strong></p><ul><li><em>Simple and Easy-to-Use:</em> Glide has a simple and intuitive API that makes it easy to load and display images in your Android app with just a few lines of code.</li><li><em>Efficient Image Caching:</em> Glide’s caching mechanism helps improve the performance of image loading by caching images in memory and on disk, reducing the need for repeated network requests.</li><li><em>Image Transformation and Customization:</em> Glide provides a wide range of image transformation options and allows you to customize the image loading process according to your specific requirements.</li><li><em>Smooth Loading and Transition:</em> Glide handles image loading seamlessly, providing smooth transitions and animated GIF support, enhancing the user experience.</li><li><em>Active Development and Community Support:</em> Glide is actively maintained and has a large community of developers, ensuring that bugs are addressed and new features are added.</li></ul><p><strong><em>Cons:</em></strong></p><ul><li><em>Limited to Image Loading:</em> Glide is primarily focused on image loading and may not provide advanced features for other media types or complex use cases.</li><li><em>Learning Curve for Advanced Features:</em> While basic image loading is straightforward, utilizing advanced features and customization options may require some learning and experimentation.</li></ul><p><strong><em>Pricing:</em></strong></p><p>Glide is an open-source library released under the Apache 2.0 license, which means it is free to use and does not have any associated costs.</p><p>It’s important to note that while Glide itself is free, there may be costs associated with other services or libraries you use in conjunction with Glide for network requests or image hosting.</p><p>Overall, Glide is a widely-used and reliable library for image loading and caching in Android applications. Its simplicity, performance optimizations, and community support make it a popular choice among Android developers.</p><p>4. <a href="https://developer.android.com/training/data-storage/room"><strong>Room:</strong></a><strong> </strong>An Android Architecture Component that provides an abstraction layer over SQLite for database operations. It simplifies database management and offers compile-time checks for SQL queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*27jl_Kss7Y0R5-GlNAltdA.jpeg" /></figure><p>Example:</p><pre>@Dao<br>interface UserDao {<br>    @Query(&quot;SELECT * FROM users&quot;)<br>    fun getAllUsers(): List&lt;User&gt;<br><br>    @Insert(onConflict = OnConflictStrategy.REPLACE)<br>    fun insertUser(user: User)<br>}<br><br>val userDao = database.userDao()<br>val users = userDao.getAllUsers()</pre><p><strong><em>Features:</em></strong></p><ul><li><em>Object-Relational Mapping (ORM):</em> Room provides an ORM layer on top of SQLite, allowing you to work with relational databases using object-oriented concepts.</li><li><em>Annotations-based Database Mapping:</em> It uses annotations to define the database schema, entities, and relationships between entities, reducing boilerplate code.</li><li><em>Type-Safe Queries: </em>Room uses compile-time verification of SQL queries, ensuring type safety and catching errors early in the development process.</li><li><em>Built-in Database Caching:</em> Room includes built-in support for caching data, reducing the need for frequent database queries and improving performance.</li><li><em>LiveData Integration:</em> It integrates seamlessly with Android Architecture Components, providing LiveData support for reactive data updates and observing database changes.</li><li><em>Migration Support:</em> Room simplifies the process of database schema migrations, allowing you to easily modify the database schema without losing existing data.</li></ul><p><strong><em>Pros:</em></strong></p><ul><li><em>Simplified Database Operations:</em> Room abstracts away many of the complexities of working with SQLite, making database operations more straightforward and less error-prone.</li><li><em>Compile-time Verification:</em> Room’s compile-time verification of queries helps catch errors early, reducing the likelihood of runtime exceptions and SQL-related bugs.</li><li><em>Improved Performance:</em> The built-in database caching and optimized queries in Room contribute to improved performance by minimizing the need for costly database operations.</li><li><em>Integration with LiveData: </em>Room’s integration with LiveData simplifies the process of updating UI components based on database changes, following reactive programming principles.</li><li><em>Android Architecture Components:</em> Room is part of the Android Architecture Components, which means it is well-integrated with other components like ViewModel and LiveData.</li></ul><p><strong><em>Cons:</em></strong></p><ul><li><strong><em>Limited Database Support:</em></strong> Room is designed specifically for SQLite databases and may not provide the same level of functionality and flexibility as standalone database solutions.</li><li><strong><em>Learning Curve:</em></strong> While Room simplifies many aspects of working with databases, there is still a learning curve involved in understanding its annotations and usage patterns.</li></ul><p>5.<a href="https://firebase.google.com/"> <strong><em>Firebase:</em></strong></a><strong><em> </em></strong>A comprehensive suite of tools provided by Google for building and managing Android apps. It offers features like real-time database, authentication, cloud messaging, analytics, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*0_fRSnvlIoG4JDtVDS6Gkw.png" /></figure><p><strong><em>Features:</em></strong></p><ul><li><em>Real-Time Database: </em>Firebase provides a real-time database that allows you to store and sync data in real-time across multiple clients.</li><li><em>Authentication: </em>Firebase offers built-in authentication services, allowing you to easily add user authentication and authorization to your app.</li><li><em>Cloud Firestore:</em> It is a flexible and scalable NoSQL document database that provides real-time syncing and offline capabilities.</li><li><em>Cloud Storage:</em> Firebase offers cloud storage for storing and serving user-generated content like images, videos, and files.</li><li><em>Cloud Functions:</em> Firebase allows you to write custom backend logic using serverless functions, triggered by events in your app.</li><li><em>Analytics and Performance Monitoring:</em> Firebase provides powerful analytics and performance monitoring tools to gain insights into app usage and performance.</li><li><em>Remote Config:</em> It enables you to dynamically update your app’s behavior and appearance without requiring a new app release.</li><li><em>Cloud Messaging:</em> Firebase Cloud Messaging allows you to send notifications and messages to your app users across different platforms.</li><li><em>Crash Reporting: </em>Firebase offers crash reporting functionality to track and analyze app crashes and errors.</li><li><em>AdMob:</em> Firebase integrates with AdMob to help you monetize your app with mobile ads.</li></ul><p><strong><em>Pros:</em></strong></p><ul><li><em>Easy Integration: </em>Firebase provides comprehensive SDKs and libraries for various platforms, making it easy to integrate and use its services.</li><li><em>Real-Time Updates:</em> Firebase’s real-time database and Firestore offer real-time syncing and updates, enabling seamless collaboration and live data updates across devices.</li><li><em>Scalability:</em> Firebase services are built to scale, allowing your app to handle large amounts of data and user traffic.</li><li><em>Analytics and Monitoring:</em> Firebase offers powerful analytics and monitoring tools that provide valuable insights into app performance and user behavior.</li><li><em>Serverless Architecture:</em> Firebase Cloud Functions enable you to write and deploy serverless functions, eliminating the need for managing server infrastructure.</li></ul><p><strong><em>Cons:</em></strong></p><ul><li><em>Vendor Lock-in:</em> Firebase is a proprietary platform, which means that switching to another backend provider can be challenging.</li><li><em>Limited Query Capabilities:</em> While Firebase offers powerful real-time syncing, its query capabilities are not as extensive as traditional databases.</li><li><em>Pricing: </em>Firebase provides a free tier with limited usage, but costs can increase as your app scales and starts consuming more resources</li></ul><p><strong><em>Pricing:</em></strong></p><p>Firebase offers a range of pricing plans, including a free tier with certain limitations and paid plans based on usage and features. The pricing depends on factors such as the number of active users, data storage, and network usage. You can refer to the Firebase pricing page for detailed information on pricing.</p><p>Overall, Firebase provides a comprehensive suite of tools and services for building and scaling mobile and web applications. Its real-time syncing, authentication, and cloud-based features make it a popular choice for developers looking for a robust backend solution.</p><p>6. <strong>Dagger 2: </strong>Dagger 2 is a dependency injection framework for Java and Kotlin applications. It helps manage the dependencies of an application by generating boilerplate code for dependency injection. Dagger 2 uses a compile-time code generation approach to provide efficient and optimized dependency injection.</p><p>Example:</p><pre>// Component Interface:<br>@Component<br>interface MyComponent {<br>    fun inject(activity: MyActivity)<br>}</pre><pre>// Module Class:<br>@Module<br>class MyModule {<br>    @Provides<br>    fun provideMyDependency(): MyDependency {<br>        return MyDependency()<br>    }<br>}</pre><pre>// Field Injection:<br>class MyActivity : AppCompatActivity() {<br>    @Inject<br>    lateinit var myDependency: MyDependency<br>    <br>    // ...<br>}</pre><p><strong><em>Pros:</em></strong></p><ul><li><em>Compile-time Safety:</em> Dagger 2 performs dependency resolution at compile-time, ensuring that all dependencies are satisfied and reducing the chances of runtime errors.</li><li><em>Performance: </em>Dagger 2 generates efficient code, eliminating the need for reflection during dependency injection and improving overall application performance.</li><li><em>Scalability:</em> Dagger 2 supports a modular approach, allowing you to easily add or modify dependencies without impacting the rest of the application.</li><li><em>Testability:</em> Dagger 2 promotes the separation of concerns, making it easier to write unit tests for individual components and dependencies.</li><li><em>Easy Configuration: </em>Dagger 2 provides a clear and explicit configuration approach, making it easier to understand and maintain the dependency graph.</li></ul><p><strong><em>Cons:</em></strong></p><ul><li>Learning Curve: Dagger 2 has a steep learning curve, especially for developers new to dependency injection concepts and annotation processing.</li><li>Boilerplate Code: Dagger 2 requires additional code annotations and setup, which can lead to increased code complexity and verbosity.</li><li>Build Time: The compile-time code generation process of Dagger 2 can increase build times, especially in large projects with complex dependency graphs.</li></ul><p><strong><em>Pricing:</em></strong></p><p>Dagger 2 is an open-source framework provided by Google and does not have any associated costs. It is freely available for use in both commercial and non-commercial projects.</p><p>Overall, Dagger 2 is a powerful dependency injection framework that provides compile-time safety, performance optimizations, and scalability for managing dependencies in Java and Kotlin applications. While it requires some initial setup and learning, it offers benefits in terms of code maintainability, testability, and application performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f1ac552237b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Commonly used Dagger Annotations in Kotlin]]></title>
            <link>https://medium.com/@manuchekhrdev/commonly-used-dagger-annotations-in-kotlin-c18a2cc2f2ab?source=rss-613bc5891dda------2</link>
            <guid isPermaLink="false">https://medium.com/p/c18a2cc2f2ab</guid>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[annotations]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Manuchekhr Tursunov]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 15:38:01 GMT</pubDate>
            <atom:updated>2023-04-28T15:38:01.802Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*5cWZkuYgC65I4CtJ_4fCAQ.png" /></figure><ul><li><strong>@Inject:</strong> Marks a constructor, field, or method as an injection point.</li></ul><p>Example:</p><pre>class Car @Inject constructor(engine: Engine) {<br>    @Inject<br>    lateinit var wheels: Wheels<br><br>    @Inject<br>    fun addCarToDriver(driver: Driver) {<br>        driver.addCar(this)<br>    }<br>}</pre><ul><li><strong>@Module</strong>: Marks a class as a provider of dependencies.</li></ul><p>Example:</p><pre>@Module<br>class CarModule {<br>    @Provides<br>    fun provideEngine(): Engine {<br>        return Engine()<br>    }<br><br>    @Provides<br>    fun provideWheels(): Wheels {<br>        return Wheels()<br>    }<br>}</pre><ul><li><strong>@Component</strong>: Marks an interface as a bridge between the provider (module) and the consumer (client).</li></ul><p>Example:</p><pre>@Component(modules = [CarModule::class])<br>interface CarComponent {<br>    fun getCar(): Car<br>}</pre><ul><li><strong>@Scope:</strong> Marks a component to limit the existence of a dependency.</li></ul><p>Example:</p><pre>@Scope<br>@Retention(AnnotationRetention.RUNTIME)<br>annotation class CarScope</pre><ul><li><strong>@Qualifier:</strong> Differentiates between objects of the same type by providing a unique identifier.</li></ul><p>Example:</p><pre>@Qualifier<br>@Retention(AnnotationRetention.RUNTIME)<br>annotation class EngineType {<br>    enum class Type {<br>        DIESEL, GASOLINE<br>    }<br><br>    companion object {<br>        fun create(type: Type) = object : EngineType {<br>            override val value = type<br>        }<br>    }<br><br>    val value: Type<br>}<br><br>@Module<br>class CarModule {<br>    @Provides<br>    @EngineType(Type.DIESEL)<br>    fun provideDieselEngine(): Engine {<br>        return DieselEngine()<br>    }<br><br>    @Provides<br>    @EngineType(Type.GASOLINE)<br>    fun provideGasolineEngine(): Engine {<br>        return GasolineEngine()<br>    }<br>}<br><br>class Car @Inject constructor(<br>    @EngineType(Type.DIESEL) val engine: Engine<br>)</pre><ul><li><strong>@Binds:</strong> This annotation is used to bind an implementation to its interface or abstract class. For example, let&#39;s say we have an interface Engine and a class PetrolEngine that implements it. We can bind them using @Binds annotation as follows:</li></ul><p>Example:</p><pre>@Module<br>abstract class EngineModule {<br>    @Binds<br>    abstract fun bindEngine(engine: PetrolEngine): Engine<br>}</pre><ul><li><strong>@Provides:</strong> This annotation is used to provide an instance of an object. For example, let’s say we want to provide a Car instance. We can use @Provides annotation as follows:</li></ul><p>Example:</p><pre>@Module<br>class CarModule {<br>    @Provides<br>    fun provideCar(engine: Engine, wheels: Wheels): Car {<br>        return Car(engine, wheels)<br>    }<br>}</pre><ul><li><strong>@Singleton</strong>: This annotation is used to ensure that only one instance of a class is created throughout the lifetime of the application. For example, let’s say we want to make sure that only one instance of Car is created. We can use @Singleton annotation as follows:</li></ul><p>Example:</p><pre>@Singleton<br>@Component(modules = [EngineModule::class, WheelsModule::class, CarModule::class])<br>interface CarComponent {<br>    fun getCar(): Car<br>}</pre><ul><li><strong>@Named:</strong> This annotation is used to provide a named instance of an object. For example, let’s say we have two implementations of Engine class, PetrolEngine and DieselEngine. We can use @Named annotation to specify which implementation to use as follows:</li></ul><p>Example:</p><pre>@Module<br>class EngineModule {<br>    @Provides<br>    @Named(&quot;petrol&quot;)<br>    fun providePetrolEngine(): Engine {<br>        return PetrolEngine()<br>    }<br><br>    @Provides<br>    @Named(&quot;diesel&quot;)<br>    fun provideDieselEngine(): Engine {<br>        return DieselEngine()<br>    }<br>}<br><br>class Car @Inject constructor(@Named(&quot;petrol&quot;) engine: Engine, wheels: Wheels) {<br>    // ...<br>}</pre><ul><li><strong>@Component.Builder: </strong>Used to define a builder for a component. This allows us to customize the component by passing different modules or dependencies during its creation.</li></ul><p>Example:</p><pre>@Component(modules = [MyModule::class])<br>interface MyComponent {<br>    fun inject(activity: MyActivity)<br><br>    @Component.Builder<br>    interface Builder {<br>        fun myModule(myModule: MyModule): Builder<br>        fun build(): MyComponent<br>    }<br>}</pre><p>In the above example, the @Component.Builder annotation is used to define the Builder interface for the MyComponent component. The Builder interface has two methods: myModule() and build(). The myModule() method takes an instance of MyModule as a parameter and returns the Builder instance itself. The build() method is used to create the MyComponent instance.</p><ul><li><strong>@Subcomponent</strong>: Used to define a subcomponent that is a child of a parent component</li></ul><p>Example:</p><pre>@Subcomponent(modules = [MySubmodule::class])<br>interface MySubcomponent {<br>    fun inject(activity: MyActivity)<br>}</pre><p>In the above example, the @Subcomponent annotation is used to define the MySubcomponent subcomponent. The MySubcomponent subcomponent is a child of a parent component and it uses the MySubmodule module to provide dependencies.</p><p>In summary, each one has its own specific use case and can be combined with others to create powerful dependency injection systems in our applications. Using these annotations can help simplify dependency injection in your Android app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c18a2cc2f2ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Popular DI: Dagger 2]]></title>
            <link>https://medium.com/@manuchekhrdev/popular-di-dagger-2-d7342e104794?source=rss-613bc5891dda------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7342e104794</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Manuchekhr Tursunov]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 14:15:20 GMT</pubDate>
            <atom:updated>2023-04-28T14:15:20.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*JMgqgjCHUIcHZGuw2YL5Pw.jpeg" /></figure><p>Dagger 2 is a popular dependency injection framework for Java and Kotlin applications. It simplifies the process of managing dependencies by providing an easy way to declare dependencies and their relationships with other components.</p><p>The basic idea behind Dagger 2 is to declare all the dependencies of a component in a single module, and then let Dagger 2 generate the code to provide those dependencies when needed. The framework is designed to be fast, efficient, and easy to use.</p><p>Dagger 2 is built on top of the concept of dependency injection, which is a technique for managing object creation and wiring. It allows you to create loosely coupled code that is easier to maintain, test, and refactor.</p><p>To use Dagger 2 in your application, you first need to add the Dagger 2 dependencies to your build.gradle file. Once you’ve done that, you can start declaring your dependencies in modules and injecting them into your classes.</p><p>Here is an example of how to use Dagger 2 to inject dependencies into a class:</p><pre>class MyClass @Inject constructor(private val myDependency: MyDependency) {<br>    // ...<br>}</pre><p>In this example, MyClass has a single constructor parameter that is annotated with @Inject. This tells Dagger 2 to provide an instance of MyDependency when creating an instance of MyClass.</p><p>To create a module that provides the MyDependency instance, you would do something like this:</p><pre>@Module<br>class MyModule {<br>    @Provides<br>    fun provideMyDependency(): MyDependency {<br>        return MyDependency()<br>    }<br>}</pre><p>In this example, MyModule declares a single method that provides an instance of MyDependency. The @Provides annotation tells Dagger 2 that this method can be used to provide the dependency.</p><p>You can then use Dagger 2 to inject the MyClass instance with the MyDependency instance like this:</p><pre>val component = DaggerMyComponent.builder().build()<br>val myClass = component.getMyClass()</pre><p>In this example, DaggerMyComponent is a Dagger 2 component that is generated by the framework. It provides the MyDependency instance to the MyClass instance through constructor injection.</p><p>Overall, Dagger 2 is a powerful and flexible dependency injection framework that can greatly simplify the process of managing dependencies in your Java or Kotlin application. By using Dagger 2, you can create more modular, testable, and maintainable code that is easier to work with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7342e104794" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sealed Class vs Sealed Interface in Kotlin]]></title>
            <link>https://medium.com/@manuchekhrdev/sealed-class-vs-sealed-interface-in-kotlin-47222335040a?source=rss-613bc5891dda------2</link>
            <guid isPermaLink="false">https://medium.com/p/47222335040a</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Manuchekhr Tursunov]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 13:58:07 GMT</pubDate>
            <atom:updated>2023-04-28T13:58:07.088Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3OPZTUfx0Q_cqOgA7BXCBA.png" /></figure><p><em>Sealed class</em> and <em>Sealed interface</em> are two features in Kotlin that allow the creation of restricted class hierarchies. Both of these constructs are used to define a finite set of possible subtypes, and prevent additional subtypes from being defined outside the declared hierarchy.</p><h4>Sealed Class:</h4><p>A sealed class is a class that can be subclassed, but only inside the same file where it is declared. This means that a sealed class cannot be directly instantiated and cannot have any other subclasses outside the file it is declared in. It is commonly used to represent a restricted hierarchy of classes.</p><p>Here is an example of a sealed class:</p><pre>sealed class Result&lt;out T&gt; {<br>    data class Success&lt;T&gt;(val data: T) : Result&lt;T&gt;()<br>    data class Error(val error: Exception) : Result&lt;Nothing&gt;()<br>}</pre><p>In this example, we have a sealed class named Result that has two subclasses, Success and Error. The Success subclass takes a generic type T as a parameter, which represents the data that is returned on success. The Error subclass takes an Exception as a parameter, which represents the error that occurred.</p><ul><li><em>Sealed classes</em> can have constructors with parameters, while sealed interfaces cannot.</li><li><em>Sealed classes </em>can have abstract methods and properties, while sealed interfaces can only have abstract methods.</li><li><em>Sealed classes</em> can be extended by classes, objects, and other sealed classes, while sealed interfaces can only be implemented by classes and objects.</li><li><em>Sealed classes</em> are often used in conjunction with when expressions to provide exhaustive pattern matching.</li></ul><p>Example:</p><pre>sealed class Animal<br>class Dog(val name: String): Animal()<br>class Cat(val name: String): Animal()<br><br>fun makeSound(animal: Animal) = when (animal) {<br>    is Dog -&gt; println(&quot;${animal.name} says woof!&quot;)<br>    is Cat -&gt; println(&quot;${animal.name} says meow!&quot;)<br>}<br><br>val myDog = Dog(&quot;Rufus&quot;)<br>val myCat = Cat(&quot;Whiskers&quot;)<br>makeSound(myDog) // outputs: &quot;Rufus says woof!&quot;<br>makeSound(myCat) // outputs: &quot;Whiskers says meow!&quot;</pre><h4>Sealed Interface:</h4><p>A sealed interface is similar to a sealed class, but it is used to represent a restricted set of interfaces rather than classes. Like sealed classes, sealed interfaces restrict the set of possible subtypes to a finite set that is defined within the same file as the sealed interface.</p><p>Here is an example of a sealed interface:</p><pre>sealed interface State {<br>    object Idle : State<br>    data class Loading(val message: String) : State<br>    data class Error(val error: Throwable) : State<br>    data class Success(val data: Any) : State<br>}</pre><p>In this example, we have a sealed interface named State that has four subtypes: Idle, Loading, Error, and Success. Each subtype represents a different state that an application might be in, such as when the application is idle, loading data, encountering an error, or successfully retrieving data.</p><ul><li>Sealed interfaces cannot have constructors with parameters, but they can have properties.</li><li>Sealed interfaces can only have abstract methods, but they can also have default implementations for those methods.</li><li>Sealed interfaces can be implemented by classes and objects, but not extended by other interfaces or sealed interfaces.</li><li>Sealed interfaces are often used as a way to define a set of related functionality that can be implemented by different classes.</li></ul><p>Example:</p><pre>sealed interface Animal {<br>    val name: String<br>    fun makeSound()<br>}<br><br>class Dog(override val name: String): Animal {<br>    override fun makeSound() {<br>        println(&quot;$name says woof!&quot;)<br>    }<br>}<br><br>class Cat(override val name: String): Animal {<br>    override fun makeSound() {<br>        println(&quot;$name says meow!&quot;)<br>    }<br>}<br><br>val myDog = Dog(&quot;Rufus&quot;)<br>val myCat = Cat(&quot;Whiskers&quot;)<br>myDog.makeSound() // outputs: &quot;Rufus says woof!&quot;<br>myCat.makeSound() // outputs: &quot;Whiskers says meow!&quot;</pre><p><em>Sealed classes</em> are used to define a restricted hierarchy of classes, while <em>Sealed interfaces </em>are used to define a set of related functionality that can be implemented by different classes. <em>Sealed classes</em> can have constructors and abstract properties, while <em>Sealed interfaces</em> cannot have constructors but can have properties and default method implementations.</p><h4>When to Use Sealed Classes vs Sealed Interfaces:</h4><p><em>Sealed classes</em> and <em>sealed interfaces</em> can both be used to define restricted class hierarchies, but they are used in different contexts. Sealed classes are typically used to represent a restricted hierarchy of classes, whereas sealed interfaces are used to represent a restricted set of interfaces.</p><p>In general, if you need to restrict the set of possible subclasses for a class hierarchy, you should use a sealed class. If you need to restrict the set of possible implementations for an interface, you should use a sealed interface.</p><p>In summary, sealed classes and sealed interfaces are powerful features in Kotlin that allow developers to define restricted class hierarchies and prevent additional subtypes from being defined outside the declared hierarchy. They are useful in situations where a finite set of possible subtypes is needed, and can help ensure that code is more reliable and less error-prone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47222335040a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Generics - in, out, where]]></title>
            <link>https://medium.com/@manuchekhrdev/kotlin-generics-in-out-where-9181ddbef01f?source=rss-613bc5891dda------2</link>
            <guid isPermaLink="false">https://medium.com/p/9181ddbef01f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Manuchekhr Tursunov]]></dc:creator>
            <pubDate>Sat, 22 Apr 2023 18:42:42 GMT</pubDate>
            <atom:updated>2023-04-22T18:42:42.567Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jKFKeIvX83KrsHfHdVHKMw.png" /></figure><p>In Kotlin, generics provide the ability to create classes, interfaces, and methods that can work with various types, without specifying the actual type until the object is created.</p><h4>In</h4><p>The &lt;in&gt; keyword in generics is used to specify a type parameter as a contravariant. Contravariant means that the type can be used as input parameters.</p><p>Here’s an example of using &lt;in&gt; with generics in Kotlin:</p><pre>interface AnimalCare&lt;in T&gt; {<br>    fun takeCareOf(animal: T)<br>}<br><br>class Vet : AnimalCare&lt;Animal&gt; {<br>    override fun takeCareOf(animal: Animal) {<br>        // do something<br>    }<br>}<br><br>class Animal {}<br><br>class Dog : Animal {}<br><br>fun main() {<br>    val animalCare: AnimalCare&lt;Dog&gt; = Vet()<br>    animalCare.takeCareOf(Dog())<br>}</pre><p>In the above example, AnimalCare is a generic interface with the type parameter T marked as in. The Vet class implements the AnimalCare interface with the type parameter Animal. The main function creates an instance of AnimalCare with the type parameter Dog, but assigns it to a variable of type AnimalCare&lt;Animal&gt;. Since Dog is a subtype of Animal, it can be passed to the takeCareOf method of the Vet class.</p><p>Using the &lt;in&gt; keyword in generics allows for a greater degree of flexibility in using classes, interfaces, and methods with different types. It is especially useful when dealing with classes that accept input parameters, such as with the takeCareOf method in the above example.</p><h4>Out</h4><p>In Kotlin, the &lt;out&gt; keyword is used to define covariance in generic classes and interfaces. It allows for a more flexible use of generics, allowing a subtype of a generic type to be used in place of the parent type.</p><p>When a generic class or interface is defined with the &lt;out&gt; keyword, it means that the type parameter can only appear in the output positions of member functions. This means that it can only be returned from functions or used as a property type.</p><p>Here’s an example of a generic interface using the &lt;out&gt; keyword:</p><pre>interface Producer&lt;out T&gt; {<br>    fun produce(): T<br>}</pre><p>In this example, T is a covariant type parameter. This interface has a single function produce() that returns an object of type T. Since T is covariant, the produce() function can return a subtype of T.</p><p>Here’s an example of how this interface can be used:</p><pre>class FruitProducer : Producer&lt;Fruit&gt; {<br>    override fun produce(): Fruit {<br>        return Apple()<br>    }<br>}</pre><p>In this example, Fruit is the type parameter for Producer. The FruitProducer class implements the Producer interface and overrides the produce() function to return an object of type Fruit, which in this case is an instance of Apple. Since T is covariant, FruitProducer is allowed to return an Apple object instead of a Fruit object.</p><p>Using the &lt;out&gt; keyword in generics can make your code more flexible and reusable. It allows you to use subtypes of a generic type where the parent type is expected, making your code more adaptable to changes in the future.</p><h4>Where</h4><p>The where keyword in Kotlin is used to add constraints on the types used as generic type parameters. It allows you to specify that a generic type parameter must be a subtype of a specific class or implement a specific interface.</p><p>Here’s an example of using where to add constraints on a generic function:</p><pre>fun &lt;T&gt; addNumbers(a: T, b: T) where T : Number {<br>    val result = a.toDouble() + b.toDouble()<br>    println(&quot;Result: $result&quot;)<br>}</pre><p>In the above example, we’ve added a constraint on the generic type parameter T using the where keyword. The constraint specifies that T must be a subtype of the Number class.</p><p>Now, let’s see how we can use this function:</p><pre>addNumbers(3, 5) // Output: Result: 8.0<br>addNumbers(2.5, 4.5) // Output: Result: 7.0<br>addNumbers(&quot;hello&quot;, &quot;world&quot;) // Compilation error: Type parameter bound for &#39;T&#39; is not satisfied</pre><p>As you can see, the function can only be called with arguments that are subtypes of Number.</p><p>You can also use the where keyword to add multiple constraints on a generic type parameter. Here&#39;s an example:</p><pre>fun &lt;T&gt; processList(list: List&lt;T&gt;) where T : CharSequence, T : Comparable&lt;T&gt; {<br>    val sortedList = list.sorted()<br>    sortedList.forEach { println(it) }<br>}</pre><p>In the above example, we’ve added two constraints on the generic type parameter T using the where keyword. The constraints specify that T must be a subtype of the CharSequence class and must also implement the Comparable interface.</p><p>Now, let’s see how we can use this function:</p><pre>val stringList = listOf(&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;)<br>processList(stringList) // Output: apple banana orange<br><br>val intList = listOf(3, 2, 1)<br>processList(intList) // Compilation error: Type parameter bound for &#39;T&#39; is not satisfied</pre><p>As you can see, the function can only be called with arguments that are subtypes of CharSequence and implement the Comparable interface.</p><p>In summary, the where keyword in Kotlin allows you to add constraints on generic type parameters to restrict the types that can be used as arguments for generic functions or classes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9181ddbef01f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Constraint Layout: Group and Barriers]]></title>
            <link>https://medium.com/@manuchekhrdev/constraint-layout-group-and-barriers-84605073088c?source=rss-613bc5891dda------2</link>
            <guid isPermaLink="false">https://medium.com/p/84605073088c</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[constraintlayout]]></category>
            <dc:creator><![CDATA[Manuchekhr Tursunov]]></dc:creator>
            <pubDate>Sat, 22 Apr 2023 18:18:48 GMT</pubDate>
            <atom:updated>2023-04-22T18:18:48.536Z</atom:updated>
            <content:encoded><![CDATA[<p><em>ConstraintLayout </em>is a flexible layout that allows you to create complex user interfaces with a flat view hierarchy. It uses constraints to position and size its child views.</p><p>In Constraint Layout, the Group and Barrier features provide a way to group multiple views and align them together. These features can help simplify the layout XML code and reduce the number of nested layouts.</p><h4>Group</h4><p>A Group is a view group that contains multiple views and can be used to apply common attributes to all of its child views. With a Group, you can set visibility, margins, padding, and more for all child views at once.</p><p>Here’s an example of using a Group in a Constraint Layout:</p><pre>&lt;androidx.constraintlayout.widget.ConstraintLayout<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;&gt;<br><br>    &lt;Button<br>        android:id=&quot;@+id/button1&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Button 1&quot; /&gt;<br><br>    &lt;Button<br>        android:id=&quot;@+id/button2&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Button 2&quot; /&gt;<br><br>    &lt;Button<br>        android:id=&quot;@+id/button3&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Button 3&quot; /&gt;<br><br>    &lt;androidx.constraintlayout.widget.Group<br>        android:id=&quot;@+id/group&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:visibility=&quot;visible&quot;<br>        app:constraint_referenced_ids=&quot;button1,button2,button3&quot;/&gt;<br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>In this example, we have three buttons and a Group element that references all three buttons. By default, the visibility of the Group element is set to “visible”, so all three buttons will be shown on the screen. However, we can change the visibility of the Group element programmatically to hide all three buttons at once.</p><h4>Barrier</h4><p>A Barrier is a view that can be used to align views together based on their position. It allows you to align views that are not adjacent to each other and avoids the need for nesting layouts.</p><p>Here’s an example of using a Barrier in a Constraint Layout:</p><pre>&lt;androidx.constraintlayout.widget.ConstraintLayout<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;&gt;<br><br>    &lt;Button<br>        android:id=&quot;@+id/button1&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Button 1&quot; /&gt;<br><br>    &lt;Button<br>        android:id=&quot;@+id/button2&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Button 2&quot;<br>        app:layout_constraintStart_toEndOf=&quot;@id/barrier&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>    &lt;Button<br>        android:id=&quot;@+id/button3&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Button 3&quot;<br>        app:layout_constraintStart_toEndOf=&quot;@id/barrier&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@id/button2&quot; /&gt;<br><br>    &lt;androidx.constraintlayout.widget.Barrier<br>        android:id=&quot;@+id/barrier&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        app:barrierDirection=&quot;left&quot;<br>        app:constraint_referenced_ids=&quot;button1,button2,button3&quot;/&gt;<br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>In this example, we have three buttons that are positioned next to each other using a Barrier element. The Barrier element is positioned to the left of all three buttons and acts as a virtual view that acts as a barrier between them. The buttons are positioned relative to the Barrier element using the layout_constraintStart_toEndOf attribute.</p><p>Overall, the Group and Barrier features in Constraint Layout provide a way to simplify and improve the layout of Android apps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84605073088c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>